-1

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?

Googlebot
  • 15,159
  • 44
  • 133
  • 229

1 Answers1

1

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
AterLux
  • 4,566
  • 2
  • 10
  • 13