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

时间:2012-12-06 15:09:41

标签: 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
</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;
?>

如果<script>...</script>之间的内容包含字符串“show_ads_”,则会删除<script></script>,但会保留所有内容。

但是上面的脚本无效。没有删除。 我想在运行它时查看源代码:

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>

2 个答案:

答案 0 :(得分:2)

替换:

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

使用:

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

答案 1 :(得分:0)

使用DOMDocument执行此操作,如下所示:

<?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>";
    }
}

?>