php pre_replace() 高亮展示文字

來源:互聯網
上載者:User
php pre_replace() 高亮顯示文字

希望在下面的文字當中高亮顯示單詞in

in the rooming, he got into the room, when he's ordered an inexpensive.

我是這樣寫的,但是連into,inexpensive, rooming,中的in 都高亮顯示了;而且空格都沒有了。

$pttn = "$newrow";

$str = preg_replace("/\s($newrow)\s/i",$pttn,$str);

如何寫才能只顯示in,而不會吧into,inexpensive, rooming,中的in也高亮??


------解決方案--------------------
你這樣寫並沒有錯誤,會只替換 in,只是要在 in 前面加個空格。
這樣寫好些
$str = "in the rooming, he got into the room, when he's ordered an inexpensive.";

$newrow = 'in';
$pttn = "$newrow";

echo $str = preg_replace("/\b($newrow)\b/i",$pttn, $str);

in the rooming, he got into the room, when he's ordered an inexpensive.

\b 表示單詞邊界

------解決方案--------------------
如果只是想做一次實現,樓上版主的回答已完全正確了。
如果想做產品級的開發,就至少需要多考慮一點點特殊情況 例如 \s


$str = "in the rooming, he got into the room, when he's ordered an inexpensive. \s";

$newrow = '\s'; // 這個會換效。
$pttn = "$newrow";

echo $str = preg_replace("/\b($newrow)\b/i",$pttn, $str);


我折騰了一下,這樣就可以替換 \s 了。


$str = "\s in the rooming, he got into \s the room, when he's ordered an inexpensive. \s";
$newrow = "\s";
$newrow2 = addslashes($newrow);
$pttn = "$newrow";
//有一個細節,我也沒搞明白 ,這裡用 \b 失效了,先把結果輸出來。
echo $str = preg_replace("/(\s+
------解決方案--------------------
^)($newrow2)(\s+
------解決方案--------------------
$)/i","\\1".$pttn."\\3", $str);

------解決方案--------------------
碰到 \s 這種保留字,總得要替換吧。?
addslashes($newrow); 一下就好了。
一個很怪的事,碰到這種保留字 \s 標紅的需求 \b 做邊界符就失效了,能解釋一下嗎?

引用:
你是在開玩笑?
preg_quote 是做什麼的?

\s 是Regex的保留字,如果作為匹配串則必須轉移!

------解決方案--------------------
引用:
我想問下我一直不理解的問題:
\\1 \\2 \\3和 $1的本質意思是什嗎?


Regex規則串中的“()”每一對錶示一個反向參考,即可被後面的規則使用。同時也會出現在結果中
既然可以用,那麼就需要知道哪個對哪個。所以規定了按出現的次序從1開始算起
在規則串中 \\1 表示第一對()中匹配到的內容
在結果中就用 \1 表示第一對()中匹配到的內容
至於表示成 $1 是因為 js 中是這樣表示的,所以 php 也允許這樣寫
寫 web 應用總是離不開 php、js、html 的,相似的文法成分用相似書寫方式,不是黑自然的嗎
  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.