3

我有文件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>
4

2 回答 2

2

代替:

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

和:

$content = preg_replace('/(<script>)([^<]*show_ads_[^<]*)(<\/script>)/s', '$2', $content);
于 2012-12-06T15:49:18.290 回答
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>";
    }
}

?>
于 2012-12-06T15:45:22.210 回答