本文介紹了PHP 字符串替換匹配整個單詞的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
限時送ChatGPT賬號..
我想用 php 替換完整的單詞
I would like to replace just complete words using php
示例:如果我有
$text = "Hello hellol hello, Helloz";
我用
$newtext = str_replace("Hello",'NEW',$text);
新文本應該看起來像
新的 hello1 你好,Helloz
NEW hello1 hello, Helloz
PHP 返回
NEW hello1 你好,NEWz
NEW hello1 hello, NEWz
謝謝.
推薦答案
您想使用正則表達式. 匹配單詞邊界.
You want to use regular expressions. The matches a word boundary.
$text = preg_replace('/Hello/', 'NEW', $text);
<小時>
如果 $text
包含 UTF-8 文本,則必須添加 Unicode 修飾符u",以便非拉丁字符不會被誤解為單詞邊界:
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);
這篇關于PHP 字符串替換匹配整個單詞的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!