2011-01-28 18 views
0

我正在阅读来自几个不同来源的HTML,我必须操作它。作为这个的一部分,我有一些preg_replace()调用,我必须替换接收到的html中的一些信息。preg_replace在输入为html时(但不是全部时间)返回null

在90%的网站上,我必须这样做,一切正常,剩下的10%在每个preg_replace()调用返回NULL。

我试着增加pcre.backtrack_limit和pcre.recursion_limit基于我发现的其他文章似乎有同样的问题,但这已无济于事。

我输出了返回'4'的preg_last_error(),PHP文档并没有证明它非常有帮助,所以如果任何人都可以在这里指出任何亮点,它可能会开始指向正确的方向,但我很难过。

之一违规的例子是:

$html = preg_replace('@<script[^>]*?.*?</script>@siu', '', $html); 

但正如我所说,这个工作90%的时间。

+0

我不知道该怎么``解释,但它似乎是多余的(相当于``,不是吗?)。 – pascal 2011-01-28 16:22:27

+0

另外为什么不包括最初的``? – pascal 2011-01-28 16:23:02

回答

2

不要使用正则表达式解析HTML。使用真正的DOM解析器:

$dom = new DOMDocument; 
$dom->loadHTML($html); 
$scripts = $dom->getElementsByTagName('script'); 
while ($el = $scripts->item(0)) { 
    $el->parentNode->removeChild($el); 
} 
$html = $dom->saveHTML(); 
0

你有坏的utf-8。

/** 
* Returned by preg_last_error if the last error was 
* caused by malformed UTF-8 data (only when running a regex in UTF-8 mode). Available 
* since PHP 5.2.0. 
* @link http://php.net/manual/en/pcre.constants.php 
*/ 
define ('PREG_BAD_UTF8_ERROR', 4); 

但是,你真的不应该使用正则表达式来解析html。使用DOMDocument

编辑:另外,我不认为这个答案是不完整的,包括You can't parse [X]HTML with regex.

0

你的#4的错误是“PREG_BAD_UTF8_ERROR”,你应该检查的网站使用的字符集至极导致此错误。

相关问题