繁体   English   中英

str_replace()在以下情况下不起作用

[英]str_replace() not working for the following case

我想使用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;
}

因此,我尝试了您的代码,并遇到了与您相同的问题。 有趣吧? 问题是,在“激励”中的“ e”和“更多”之间实际上还有另一个字符,如果这样做,您可以看到它,将$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 ... ,看! 这是我们的神秘人物,字符代码为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})但是在两种情况下,您都可能希望保持灵活性。

您可以使用以下方法更简单地执行此操作:

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

它将替换所有&nbsp; 带有标准空格的字符。

现在,您可以继续执行代码,但替换所有的&nbsp; 定期 空间

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM