本文介紹了PHP 字符串替換匹配整個(gè)單詞的處理方法,對(duì)大家解決問(wèn)題具有一定的參考價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)吧!
問(wèn)題描述
限時(shí)送ChatGPT賬號(hào)..
我想用 php 替換完整的單詞
I would like to replace just complete words using php
示例:如果我有
$text = "Hello hellol hello, Helloz";
我用
$newtext = str_replace("Hello",'NEW',$text);
新文本應(yīng)該看起來(lái)像
新的 hello1 你好,Helloz
NEW hello1 hello, Helloz
PHP 返回
NEW hello1 你好,NEWz
NEW hello1 hello, NEWz
謝謝.
推薦答案
您想使用正則表達(dá)式. 匹配單詞邊界.
You want to use regular expressions. The matches a word boundary.
$text = preg_replace('/Hello/', 'NEW', $text);
<小時(shí)>
如果 $text
包含 UTF-8 文本,則必須添加 Unicode 修飾符u",以便非拉丁字符不會(huì)被誤解為單詞邊界:
If $text
contains UTF-8 text, you'll have to add the Unicode modifier "u", so that non-latin characters are not misinterpreted as word boundaries:
$text = preg_replace('/Hello/u', 'NEW', $text);
這篇關(guān)于PHP 字符串替換匹配整個(gè)單詞的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!
【網(wǎng)站聲明】本站部分內(nèi)容來(lái)源于互聯(lián)網(wǎng),旨在幫助大家更快的解決問(wèn)題,如果有圖片或者內(nèi)容侵犯了您的權(quán)益,請(qǐng)聯(lián)系我們刪除處理,感謝您的支持!