str_replace()不适用于以下情况

时间:2015-11-13 00:14:17

标签: php str-replace findandmodify

我想使用str_replace()在html字符串周围放置span元素,以突出显示它们。

但是当字符串中有 时,以下内容不起作用。我尝试用 替换' ',但这没有帮助。

LIVE示例

您可以使用以下代码重新创建问题:

$str_to_replace = "as a way to incentivize more purchases.";

$replacement = "<span class='highlighter'>as a way to incentivize&nbsp;more purchases.</span>";

$subject = file_get_contents("http://venturebeat.com/2015/11/10/sources-classpass-raises-30-million-from-google-ventures-and-others/");

$output = str_replace($str_to_replace,$replacement,$subject);

.highlighter{
    background-collor: yellow;
}

2 个答案:

答案 0 :(得分:1)

所以我尝试了你的代码并遇到了你遇到的同样问题。有意思吧?问题是,实际上&#34; e&#34;之间存在另一个角色。 in&#34; incentivize&#34;和#34;更多&#34;,如果您这样做,可以看到它,将$subject分成两部分,在文本to incentivize之前和之后:

// splits the webpage into two parts
$x = explode('to incentivize', $subject);

// print the char code for the first character of the second string
// (the character right after the second e in incentivize) and also
// print the rest of the webpage following this mystery character
exit("keycode of invisible character: " . ord($x[1]) . " " . $x[1]);

打印:keycode of invisible character: 194 Â more ...,看!这是我们的神秘人物,它有charcode 194!

也许这个网站嵌入这些角色使你很难做到你正在做的事情,或者它只是一个错误。在任何情况下,您都可以使用preg_replace代替str_replace并更改$str_to_replace,如下所示:

$str_to_replace = "/as a way to incentivize(.*?)more purchases/";

$replacement = "<span class='highlighter'>as a way to incentivize more purchases.</span>";

$subject = file_get_contents("http://venturebeat.com/2015/11/10/sources-classpass-raises-30-million-from-google-ventures-and-others/");

$output = preg_replace($str_to_replace,$replacement,$subject);

现在这可以满足您的需求。 (.*?)处理神秘的隐藏角色。您可以进一步缩小此正则表达式,或至少将其限制为最大字符数([.]{0,5}),但在任何一种情况下,您都可能希望保持灵活性。

答案 1 :(得分:0)

你可以用这个更简单的方式做到这一点:

$subject = str_replace("\xc2\xa0", " ", $subject);

将使用标准空格替换所有&nbsp;个字符。

您现在可以继续使用您的代码,但将&nbsp;替换为常规空间