使用 preg_replace 删除 <script> 标签

mat*_*ner 6 php regex

我正在过滤字符串(从文本文件中提取),并使用 preg_replace 删除所有 和 标签。由于某种原因,它删除了实际的文本“script”,但保留了 <> 和 . 我尝试过在 /< 中进行替换(尝试将其视为文字),但这只会产生错误。我怎样才能把括号也去掉呢?输入是<script>Text</script> 代码如下:

$file = file_get_contents($directory . "original-" . $name);
$file = htmlentities($file);
$file = preg_replace('<script>', '', $file);
$file = preg_replace('<\script>', '', $file);
Run Code Online (Sandbox Code Playgroud)

这是输出:

  <>TEXT</>
Run Code Online (Sandbox Code Playgroud)

Ale*_*lex 8

答案是

$html = preg_replace('#<script(.*?)>(.*?)</script>#is', '', $html);
Run Code Online (Sandbox Code Playgroud)

但你可能想看看这个strip_tags函数

  • 因为 1. 这个问题已经在这个网站上解释了一百万次,而且这个问题每隔一天就会出现一次。2. 这很可能不能用正则表达式来解决,而应该使用 strip_tags 来代替。 (2认同)