[英]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 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);
它將替換所有
帶有標准空格的字符。
現在,您可以繼續執行代碼,但替換所有的
定期 空間
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.