phpregexstr-replaceword-boundary

How to replace individual words in a string in PHP?


I need to replace words by substitutes given by an array as

$words = array(
'one' => 1,
'two' => 2,
'three' => 3
);

$str = 'One: This is one and two and someone three.';

$result = str_ireplace(array_keys($words), array_values($words), $str);

but this method changes someone to some1. I need to replace individual words.


Solution

  • You can use word boundries in a regex to require a word match.

    Something like:

    \bone\b
    

    would do it. preg_replace with the i modifier is what you'd want to use in PHP.

    Regex demo: https://regex101.com/r/GUxTWB/1

    PHP Usage:

    $words = array(
    '/\bone\b/i' => 1,
    '/\btwo\b/i' => 2,
    '/\bthree\b/i' => 3
    );
    $str = 'One: This is one and two and someone three.';
    echo preg_replace(array_keys($words), array_values($words), $str);
    

    PHP Demo: https://eval.in/667239

    Output:

    1: This is 1 and 2 and someone 3.