PHP string replace match whole word PHP string replace match whole word php php

PHP string replace match whole word


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


multiple word in string replaced by this

    $String = 'Team Members are committed to delivering quality service for all buyers and sellers.';    echo $String;    echo "<br>";    $String = preg_replace(array('/\bTeam\b/','/\bfor\b/','/\ball\b/'),array('Our','to','both'),$String);    echo $String;    Result: Our Members are committed to delivering quality service to both buyers and sellers.


Array replacement list: In case your replacement strings are substituting each other, you need preg_replace_callback.

$pairs = ["one"=>"two", "two"=>"three", "three"=>"one"];$r = preg_replace_callback(    "/\w+/",                           # only match whole words    function($m) use ($pairs) {        if (isset($pairs[$m[0]])) {     # optional: strtolower            return $pairs[$m[0]];              }        else {            return $m[0];              # keep unreplaced        }    },    $source);

Obviously / for efficiency /\w+/ could be replaced with a key-list /\b(one|two|three)\b/i.