Search code examples
arrayspreg-replace-callback

use preg_replace_callback with array


I know this has been asked elsewhere, but I can't find the precise situation (and understand it!) so I'm hoping someone might be able to help with code here.

There's an array of changes to be made. Simplified it's:

$title = "Tom's wife is called Tomasina";

$change_to = array(
   "Tom"        => "Fred",
   "wife"       => "girlfriend",
);

$title = preg_replace_callback('(\w+)', function( $match )use( $change_to ) {
    return $array[$match[1]];
}, $title);

I'm hoping to get back "Fred's girlfriend is called Tomasina" but I'm getting all sorts of stuff back depending on how I tweak the code - none of which works!

I'm pretty certain I'm missing something blindingly obvious so I apologise if I can't see it!

Thank you!


Solution

  • There are several issues:

    • Use $change_to in the anonymous function, not $array
    • Use regex delimiters around the pattern (e.g. /.../, /\w+/)
    • If there is no such an item in $change_to return the match value, else, it will get removed (the check can be performed with isset($change_to[$match[0]])).

    Use

    $title = "Tom's wife is called Tomasina";
    
    $change_to = array(
       "Tom"        => "Fred",
       "wife"       => "girlfriend",
    );
    
    $title = preg_replace_callback('/\w+/', function( $match ) use ( $change_to ) {
        return isset($change_to[$match[0]]) ? $change_to[$match[0]] : $match[0];
    }, $title);
    echo $title;
    // => Fred's girlfriend is called Tomasina
    

    See the PHP demo.

    Also, if your string can contain any Unicode letters, use '/\w+/u' regex.