Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 952
NVG Avatar asked Aug 06 '10 17:08

NVG


People also ask

How to replace word from string in php?

The str_replace() function replaces some characters with some other characters in a string. This function works by the following rules: If the string to be searched is an array, it returns an array. If the string to be searched is an array, find and replace is performed with every array element.

How do you search a specific word in PHP file and replace with a new word?

In order to do this task, we have the following methods in PHP: Method 1: Using str_replace() Method: The str_replace() method is used to replace all the occurrences of the word W1 by replacing word W2 in the given string str. Example: PHP.

What is the difference between Str_replace and Preg_replace?

str_replace replaces a specific occurrence of a string, for instance "foo" will only match and replace that: "foo". preg_replace will do regular expression matching, for instance "/f. {2}/" will match and replace "foo", but also "fey", "fir", "fox", "f12", etc.

How do you replace a whole word in Python?

Use re. sub instead of normal string replace to replace only whole words.So your script,even if it runs again will not replace the already replaced words.


1 Answers

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

$text = preg_replace('/\bHello\b/', '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('/\bHello\b/u', 'NEW', $text); 
like image 145
Lethargy Avatar answered Sep 24 '22 08:09

Lethargy