正则表达对*和()和变性的“过敏”?

时间:2012-06-14 21:13:01

标签: php regex

我有以下两个正则表达式,我想知道为什么它们不起作用的原因是什么:

$regex='#<br><h1 class="band name">(.+?)</h1><span class="bandinfotop">#';
preg_match($regex,$content,$match);
$name=$match[1];

在它确实有效的情况下,所选字符串类似于例如**Häuptling和“(R)BrechendeZäune”。它起作用的一个例子是“!n:fact”。

现在我想知道是否因为字符串中的任何特定符号弄乱了我的正则表达式?像变形虫一样?

稍后在代码中我这样做:

$name=strip_tags($name);
$name=htmlentities($name,null,"UTF-8");
if($name=="") $name="NULL";

对于没有找到匹配的那些,它会回显“NULL”。

感谢任何帮助! 查尔斯

编辑1 它似乎是最后三行 - 当最后一行之前的两个被注释掉时,它运行正常。

解 当我在htmlentities()中删除参数null和“UTF-8”时,它以某种方式工作。有谁知道为什么?

2 个答案:

答案 0 :(得分:2)

如果您的报废网站具有云杉并移除<br>或在</h1><span之间添加空格,您的正则表达式将会中断,会发生什么情况。不要使用正则表达式进行html解析!

改为使用像simplehtmldom这样的dom解析器,或者只使用phps native DOMDocument

<?php 
$source = '<br><h1 class="band name">Häuptling and "(R) Brechende Zäune</h1><span class="bandinfotop">';


header('Content-Type: text/html; charset=utf-8');
$return = array();
$dom = new DOMDocument("1.0","UTF-8");
@$dom->loadHTML($source);
$dom->preserveWhiteSpace = false;

foreach($dom->getElementsByTagName('h1') as $headings) {
    if($headings->getAttribute('class') == "band name"){
        $title = $headings->nodeValue;
    }
}

echo $title; //Häuptling and "(R) Brechende Zäune
?>

答案 1 :(得分:1)

解析比正则表达式更可靠:

   $yourhtml = '<br><h1 class="band name">argh!</h1><span class="bandinfotop">';
   $dom = new DOMDocument();
   $dom->recover = true;
   $dom->loadHTML($yourhtml);
   $x = new DOMXPath($dom);
   foreach($x->query('//h1[@class="band name"]') as $node) var_dump($node->nodeValue);

但你的正则表达式也有效:

   $content = '<br><h1 class="band name">**Häuptling and "(R) Brechende Zäune"</h1><span class="bandinfotop">';
   $regex='#<br><h1 class="band name">(.+?)</h1><span class="bandinfotop">#';
   preg_match($regex,$content,$match);
   var_dump(htmlentities(strip_tags($match[1]),null,'utf-8'));
   $content = '<br><h1 class="band name">!n:fact"</h1><span class="bandinfotop">';
   preg_match($regex,$content,$match);
   var_dump(htmlentities(strip_tags($match[1]),null,'utf-8'));

   //string(47) "**H&auml;uptling and "(R) Brechende Z&auml;une""
   //string(8) "!n:fact""

...所以你的特殊问题是其他地方。

相关问题