0

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

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


现场示例

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

$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;
}
4

2 回答 2

1

因此,我尝试了您的代码并遇到了与您相同的问题。很有趣,对吧?问题是“激励”中的“e”和“more”之间实际上还有另一个字符,如果你这样做,你可以看到它,分成$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})但无论哪种情况,您都可能希望保持灵活性。

于 2015-11-13T01:36:49.740 回答
1

您可以通过以下方式以更简单的方式执行此操作:

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

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

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

于 2015-11-13T01:41:34.220 回答