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.
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.
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.
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.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With