Home>Article>Backend Development> How to implement word replacement in php
How to implement word replacement in php: first create a PHP sample file; then define a variable; finally implement the word through "preg_replace('/\bHello\b/', 'NEW', $text);" Just replace it.
The operating environment of this article: windows7 system, PHP7.1 version, DELL G3 computer
Specific questions:
How to implement word replacement in php? PHP string replace matches the whole word
I want to replace the whole word using php
Example:
If I have
$text = "Hello hellol hello, Helloz";
I use
$newtext = str_replace("Hello",'NEW',$text);
The new text should look like this
NEW hello1 hello, Helloz
PHP returns
NEW hello1 hello, NEWz
How to implement:
You want to use regular expressions. \b matches word boundaries.
$text = preg_replace('/\bHello\b/', 'NEW', $text);
If $text contains UTF-8 text, you must add the Unicode modifier "u" so that non-Latin characters are not misinterpreted as word boundaries:
$text = preg_replace('/\bHello\b/u', 'NEW', $text);
Recommended learning:《PHP video tutorial》
The above is the detailed content of How to implement word replacement in php. For more information, please follow other related articles on the PHP Chinese website!