Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
305 views
in Technique[技术] by (71.8m points)

PHP string replace match whole word

I would like to replace just complete words using php

Example : If I have

$text = "Hello hellol hello, Helloz";

and I use

$newtext = str_replace("Hello",'NEW',$text);

The new text should look like

NEW hello1 hello, Helloz

PHP returns

NEW hello1 hello, NEWz

Thanks.

question from:https://stackoverflow.com/questions/3426265/php-string-replace-match-whole-word

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You want to use regular expressions. The matches a word boundary.

$text = preg_replace('/Hello/', 'NEW', $text);

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...