php正则表达式问题


php regular expression issue

是的,我知道在html上使用正则表达式不是首选,但我仍然困惑于为什么这不起作用:

我正试图从文档中删除"头">
这是文件:

<html>
 <head>
   <!--
     a comment within the head
     -->
 </head>
 <body>
stuff in the body
 </body>
</html>

我的代码:

$matches = array(); $result = preg_match ('/(?:<head[^>]*>)(.*?)(<'/head>)/is', $contents, $matches); 
var_dump ($matches);

这实际上并不奏效。这是我看到的输出:

array(3) { [0]=> string(60) " " [1]=> string(47) " " [2]=> string(7) "" }

但是,如果我将HTMI文档调整为没有注释

我错过了什么?

谢谢!

您的正则表达式看起来不错,但提取<head>;您想要移除头部。尝试改用preg_replace

$without_head = preg_replace ('/(?:<head[^>]*>)(.*?)(<'/head>)/is', '', $contents);

您的脚本运行良好,由于转储中的HTML,它无法正确显示(您可以通过var_dump输出中的长度来判断(。尝试:

$result = preg_match ('/(?:<head[^>]*>)(.*?)(<'/head>)/is', $contents, $matches); 
ob_start(); // Capture the result of var_dump
var_dump ($matches);
echo htmlentities(ob_get_clean()); // Escape HTML in the dump

此外,如前所述,您需要使用preg_replace将匹配替换为'',以便实际移除头部。

php > $str=<<<EOS
<<< > <head>
<<< >    <!--
<<< >      a comment within the head
<<< >      -->
<<< >  </head>
<<< > EOS;
php > $r=preg_match('/(?:<head[^>]*>)(.*?)(<'/head>)/is',$str,$matches);
php > var_dump($r);
int(1)
php > var_dump($matches);
array(3) {
  [0]=>
  string(63) "<head>
   <!--
     a comment within the head
     -->
 </head>"
  [1]=>
  string(50) "
   <!--
     a comment within the head
     -->
 "
  [2]=>
  string(7) "</head>"
}

你是说要用preg_replace吗?

php > $r=preg_replace('/(?:<head[^>]*>)(.*?)(<'/head>)/is','',$str);
php > var_dump($r);
string(0) ""