user3325376 user3325376 - 3 years ago 124
PHP Question

foreach in foreach overwrite result

here is my PHP code:

1- I have some HTML codes with javascript

line 2

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

3- I have some allow list array
(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
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);


Answer Source

You can make use of flag variable. Try below code

$content = '<br>
<script src=""></script>
<h1> some html codes</h1>
<script src=""></script>
<h2> etc </h2>
<script src=""></script>
<!-- comment -->
<script src=""></script>
<script src=""></script>
<script src=""></script>
<script src=""></script>

# extract javascripts to array

$allowed_js = array(

    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;


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