Search code examples
phpmatchremove-if

remove tag but keep content between tag if matched string


I have file php:

<?php
$content = "
<script>
include string show_ads_1 and other string 1
</script>

<script>
include string show_ads_2 and other string 2
</script>

<script>
include string show_ads_x and other string x
</script>

<script>
not include 'show  _  ads  _  x' --> keeping this
</script>

<script type=\"text/javascript\">
include string 'show_ads_x' but keeping this because <script type='text/javascript'> not <script>
</script>
";

//Only remove tag <script></script> if includes "show_ads" string
$content = preg_replace('/(<script>)(show_ads.*?)(<\/script>)/s', '$2', $content);
echo $content;
?>

If content between <script>...</script> include string "show_ads_" it will remove <script> and </script> but keep all content.

But above script is not working. Nothing removed. I want when run it and view source code it looks like:

include string show_ads_1 and other string 1



include string show_ads_2 and other string 2



include string show_ads_x and other string x


<script>
not include 'show  _   ads  _  x' --> keeping this
</script>

<script type="text/javascript">
include string 'show_ads_x' but keeping this because <script type='text/javascript'> not <script>
</script>

Solution

  • Replace:

    $content = preg_replace('/(<script>)(show_ads.*?)(<\/script>)/s', '$2', $content);
    

    With:

    $content = preg_replace('/(<script>)([^<]*show_ads_[^<]*)(<\/script>)/s', '$2', $content);