【发布时间】:2016-02-13 02:05:28
【问题描述】:
我正在尝试使用str_replace() 来搜索和替换 html 页面中的特定字符串。例如,我正在替换:
$search_string = 'The new funding follows a <a href="http://blog.classpass.com/2015/01/15/were-so-excited-to-share-our-biggest-news-ever/">$40 million raise announced</a> in January.';
与
$replacement = '<span class="newString">The new funding follows a <a href="http://blog.classpass.com/2015/01/15/were-so-excited-to-share-our-biggest-news-ever/">$40 million raise announced</a> in January.</span>';
$subject = file_get_contents("some-web-site.html");
$new_string = str_replace($search_string, $replacement, $subject);
但是,当$subject 包含大量html 时,替换不起作用。如果我只是这样做:
$subject = "some text some text " . $search_string . "some text some text";
句子被正确替换。这个问题似乎特别是由于&nbsp; 元素而出现的。如果$search_string 不包含&nbsp;,那么无论$subject 元素的复杂性如何(即即使它包含完整的网页)。
知道为什么吗?
【问题讨论】:
-
您使用的是
preg_replace还是str_replace?你提到两者。用"&nbsp;"之类的东西做str_replace似乎对我来说效果很好。preg_replace可能会失败,因为它遇到了未转义的元字符,例如&. -
对不起,我到处都在使用 str_replace。但是如果可以解决问题,我会使用 preg_replace
标签: php html replace str-replace