user3325376 user3325376 - 3 years ago 112
PHP Question

foreach in foreach overwrite result

here is my PHP code: https://eval.in/871659

1- I have some HTML codes with javascript

$content
line 2

2- I want to extract javascript codes to array line 17

3- I have some allow list array
$allowed_js
(the javascript codes that can be on my HTML) line 20

4- I want to remove not allowed javascript line 26 - 35

The problem is in section 4, because I am using foreach in foreach, every javascript
$matches array
check as count as
$allowd_js array
which is true,

but the problem is it's it's get replace string if it detects not allowed string, so basically for every javascript, there is only one allowed word (that contained in
$allowed_js array
), so in every case it's will be replaced

I also tried using
break
but it's not working

also, i tried this loop, but it's not working too

$allow_count = count($allowed_js)-1;
foreach ($matches[0] as $key => $value) {
for ($i = 0; $i <= $allow_count ; $i++) {
if (strpos($value,$allowed_js[$i]) == false) {
$content = str_replace($value,"",$content);
//break;
}

}
}

Answer Source

You can make use of flag variable. Try below code

<?php
$content = '<br>
<script src="https://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<h1> some html codes</h1>
<script src="googlead.com/abc.js"></script>
<h2> etc </h2>
<script src="site1.com/sdfffe.js"></script>
<!-- comment -->
<script src="site2.com/something.js"></script>
<p>123</p>
<script src="site3.com/xyz.js"></script>
<script src="site4.com/qwerty.js"></script>
<script src="site5.com/sdfffe.js"></script>
';

# extract javascripts to array
preg_match_all('~<script.*?</script>~si',$content,$matches);


$allowed_js = array(
    "googlecode",
    "googlead"
    );


    foreach ($matches[0] as $key => $value) {
           $valid = 0;
        foreach ($allowed_js as $aval) {
            if (strpos($value,$aval) !== false) {
                #it's detected as allowed , so nothing to do
                $valid = 1;
            } 
        }
        if($valid == 0){
             $content = str_replace($value,"",$content);
        }
    }

echo $content;

DEMO

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download