Search code examples
phpregexpreg-replace-callback

PHP: preg_replace_callback changes the order of the result


I have the following code

return preg_replace_callback(
    "#\{gallery: '(.+?)'(?: dir: ([0-1]))?\}#i",
    create_function('$i', 'echo $i[1];' ),
    $string);

My problem is that if my string looks like this:

top
{gallery: 'images/'}
center
{gallery: 'images/characters'}
bottom

when it gets rendered it looks like this:

images/
images/characters
top center bottom

why is the order being changed and bringing the replaced code to the top and everything else to the bottom, even the thing in the middle?


Solution

  • You should use return statement inside the replacement callback:

    $string = "top {gallery: 'images/'} center {gallery: 'images/characters'} bottom";
    $string = preg_replace_callback(
      "#\{gallery: '(.+?)'(?: dir: ([0-1]))?\}#i", 
      create_function('$i', 'return $i[1];'), 
      $string
    );
    echo $string . PHP_EOL;
    
    // Outputs: top images/ center images/characters bottom