Php 删除标记,但如果字符串匹配,则保留标记之间的内容

Php 删除标记,但如果字符串匹配,则保留标记之间的内容,php,match,remove-if,Php,Match,Remove If,我有一个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 <

我有一个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;
?>
用于执行该操作,如下所示:

<?php

$dom = new DOMDocument();
$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>
    include string bla bla bla
    </script>

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

    <script type='text/javascript'>
    must keeping script
    </script>

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

$dom->loadHTML($content);
$scripts = $dom->getElementsByTagName('script');

foreach ($scripts as $script) {
    if (!$script->hasAttributes()) {
        if (strstr($script->nodeValue, "show_ads_")) {
            echo $script->nodeValue . "<br>";
        }
    } else {
        echo "<script type='text/javascript'>$script->nodeValue</script>" . "<br>";
    }
}

?>
替换:

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


$content=preg_replace('/())([^这怎么会“不起作用”?您的“查看源代码”示例显示,脚本标记已被删除,正如您在需求中所述。@MarcB我想他想了解的是什么;当您查看源代码时,
可能会重复自己的问题?@Marc B:运行文件并查看空白页。查看源代码,无任何更改。我希望页面显示:“包括字符串显示\u广告\u 1和其他字符串1”“包括字符串显示\u广告\u 2和其他字符串2”“包括字符串显示\u广告\u n和其他字符串n”“查看不包含在上述和中的源代码below@Daryl吉尔:不,先生,这个问题已经解决了,但是删除所有…我只想删除包含字符串的问题。我会删除旧问题哇,谢谢snipes83。它工作得更好,因为我从其他网站获取内容。
$content = preg_replace('/(<script>)(show_ads.*?)(<\/script>)/s', '$2', $content);
$content = preg_replace('/(<script>)([^<]*show_ads_[^<]*)(<\/script>)/s', '$2', $content);