Str_replace: match the whole word

Since it str_replace()matches the ": Name" in ": Name: Name_en" twice, I want to combine the results for the whole word only. I wanted to switch on preg_replace()because of this answer .

$str = ":Name :Name_en";
echo $str . chr(10);
$str = preg_replace('/\b' . ':Name' . '\b/i', '"Test"', $str);
echo $str;

But this does not work because of the colon. No replacement occurs. What will RegExp look like?

\b- word boundary. But I think that the colon does not belong to such a word boundary.

+5
source share
3 answers

You do not need the word boundary at the beginning of the line:

$str = preg_replace('/:Name\b/i', '"Test"', $str);
+9
source

If you are using PHP 5+, you can still use str_replace.

$str = ":Name :Name_en";
echo $str . chr(10);

// The final int limits the function to a single replace.
$str = str_replace(':Name', '"Test"', $str, 1);

echo $str;
+1
source

, , - , :

$words=array("_saudation_"=>"Hello", "_animal_"=>"cat", "_animal_sound_"=>"MEooow");
$source=" _saudation_! My Animal is a _animal_ and it says _animal_sound_ ,  _no_match_";

echo (preg_replace_callback("/\b_(\w*)_\b/", function($match) use ($words) { if(isset($words[$match[0]])){
 return ($words[$match[0]]);}else{ return($match[0]);}},  $source));

Returns: Hello! My Animal is a cat, and she says that MEooow, _no_match _

Please note that although "_no_match_" does not have a translation, it will match during regular expression but will retain its key.

+1
source

All Articles