2

我有从我的其他网站获取内容的文件。它包括很多:

<script>
[random] string 1
</script>

<script>
[random] string 2
</script>
....
<script>
[random] string n
</script>

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

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

我想删除<script></script>但使用 PHP 在它们之间保留内容“[随机] 字符串 ...”。

注意: str_replace 可以删除它们,但可能会使其他脚本<script type="text/javascript">must keeping</script><script type='text/javascript'>must keeping</script>. 它将丢失</script>必须保留脚本的紧密标记

感谢您的帮助

//解决:

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

无论如何,谢谢你的帮助

4

5 回答 5

6
<?php
 $text = '<p>Test paragraph.</p><!-- Comment --> <a href="#fragment">Other text</a>';
 echo strip_tags($text);

 ?>

要获取有关条形标签的更多信息,请参阅http://php.net/manual/en/function.strip-tags.php

于 2012-12-06T07:07:27.580 回答
3

尝试这个

$content = "
    <script>
    [random] string 1
    </script>

    <script>
    [random] string 2
    </script>
    ....
    <script>
    [random] string n
    </script>    
";

$content = str_replace(array("<script>", "</script>"), "", $content);

编辑:既然你想摆脱<script></script>并同时保持<script type="text/javascript"></script>,并且因为使用正则表达式来解决这类问题是一个坏主意,那么尝试使用DOMDocument这样的:

$dom = new DOMDocument();

$content = "
    <script>
    [random] string 1
    </script>

    <script>
    [random] string 2
    </script>
    ....
    <script>
    [random] string n
    </script>

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

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

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

foreach ($scripts as $script) {
    if (!$script->hasAttributes()) {
        echo $script->nodeValue . "<br>";
    }
}

这将输出:

[随机] 字符串 1
[随机] 字符串 2
[随机] 字符串 n

于 2012-12-06T07:10:39.823 回答
0

如果文件是 test.txt,请使用此代码

<?php
$myFile = "test.txt";
$fh = fopen($myFile, 'r');
$theData = fread($fh, 5000);
echo str_replace("</script>","",str_replace("<script>","",$theData));
fclose($fh);
 ?>
于 2012-12-06T07:13:01.137 回答
0

如果内容是字符串类型,那么您可以使用str-replacestr-ireplace

于 2012-12-06T06:55:48.113 回答
0

然后尝试 strip_tags 函数http://php.net/manual/en/function.strip-tags.php

于 2012-12-06T07:01:05.337 回答