1

Need to find a single <script> condition </script> that contains condition. The example below contains 4 tags, i need to match the second tag that contains condition and discard the others. Starts with <script>. Before the condition could be space or new line, and than the condition like if (window.location.href == bar) { } and than could be space or new line, and the end </script>.

<script>                  <!-- discard --->
other stuff
not to be found
</script>                 


<script>                  <!-- MATCH --->

if (window.location.href == bar) {         
do something                 
}

</script>                

<script>                 <!-- discard --->
other stuff
not to be found
</script>                

<script>                 <!-- discard --->
other stuff
not to be found
</script>

Thanks in advance

1
  • I hope you were expecting this result. Commented Apr 30, 2017 at 3:07

1 Answer 1

1

Here you should use DOMDocument instead of Regex for matching tags and its required content.

Try this code snippet here

<?php
ini_set('display_errors', 1);
$object= new DOMDocument();
$object->loadHTML('<html><body><script>                  <!-- discard --->
other stuff
not to be found
</script>                 

<script>                  <!-- MATCH --->

if (window.location.href == bar) {         
do something                 
}

</script>                

<script>                 <!-- discard --->
other stuff
not to be found
</script>                

<script>                 <!-- discard --->
other stuff
not to be found
</script></body></html>');
$tagsToRemove=array();
foreach($object->getElementsByTagName("script") as $element)
{
    if($element instanceof  DOMElement)
    {
        if(!preg_match("/if\s*\(/i", $element->nodeValue))
        {
            $tagsToRemove[]=$element;
        }
    }
}
foreach($tagsToRemove as $element)
{
    $element->parentNode->removeChild($element);
}
echo $object->saveHTML();
Sign up to request clarification or add additional context in comments.

2 Comments

Actually i'm using cURL to get the html.
@Avel can you share your complete HTML? but i think my above example will work fine for your complete HTML as well

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.