只提取带有preg_match_all的开始和结束脚本标记


Extract only begining and end script tag with preg_match_all

Html:

<script type="text/javascript"> ..code.. </script>
<script type="text/javascript"> ..code.. </script>
<script> ..code.. </script>
<script type="text/javascript"> ..code.. </script>

我想看的:

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

我的表达:

preg_match_all('/<script.*> (<'/script>)/i',$html, $result);

我做不到。

您可以使用这个:

$html = preg_replace('~<script[^>]*>'K[^<]*(?=</script>)~i', '', $html);

或者这是为了获得更多性能:

$html = preg_replace('~<script[^>]*+>'K[^<]*+(?=</script>)~i', '', $html);

请注意,如果您确定小写,则可以删除i

'K从匹配结果重置匹配的开始

(?=</script>)是一个零宽度断言,意思是"后面跟着</string>"。这不是比赛结果的一部分。这只是一张支票。

从这里开始:

function stripscript($code) {
  $code = preg_replace('/<script'b[^<]*(?:(?!<'/script>)<[^<]*)*<'/script>/i', '<script type="text/javascript"></script>', $code);
  return $code;
}

Codepad示例:此处