使用preg_replace函数出错


Error using preg_replace function

我只想替换

<span class="google-src-text" style="direction: ltr; text-align: left">any character</span>

一行一行的空格在这个源http://persianfox.ir/html.html和我的PHP代码是

$content = file_get_contents('path/to/html.html');
$content = str_replace('>', ">'n", $content);
echo preg_replace('/<span class="google-src-text" style="direction: ltr; text-align: left">.*.<'/span>/', ' ', $content);

但是这段代码会替换所有以<span class="google-src-text" style="direction: ltr; text-align: left">开头,最后一个是</span>的内容

*默认为贪婪,您需要将其更改为懒惰,如下所示:

preg_replace('/<span class="google-src-text" style="direction: ltr; text-align: left">.*?<'/span>/', ' ', $content);
//                                                               Note the question mark ^

这将匹配*直到第一个</span>,请注意,如果您有一个嵌套的span在里面,它将不会获取所有的方式到最后。

这就是为什么你不应该用Regex解析HTML ,而应该使用合适的HTML DOM解析器

如果你的"any character"中没有HTML,这个方法就有效。

/<span class="google-src-text" style="direction: ltr; text-align: left">([^<]{1,})<'/span>/