Search code examples
phpregexpreg-replacepreg-replace-callback

using preg_replace_callback for multiple matches


I tried a simple regex using preg_replace_callback as

$str = 'Key Value';
$str = preg_replace_callback('/(key) (.*?)/', function($m) { 
return $m[2].$m[1];
}, $str);

echo $str;

I expected the output would be

ValueKey

but it doesn't. Where did I make the mistake?


Solution

  • First you have to remove ? after * in the pattern. Otherwise it'll stop matching as soon as possible (i.e. after none characters).

    Second. You either have to use case insensitive matching, adding i parameter, or change the case of word key in the pattern:

    <?php
    $str = 'Key Value';
    $str = preg_replace_callback('/(key) (.*)/i', function($m) { 
    return $m[2].$m[1];
    }, $str);
    
    echo $str; // ValueKey