-1

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?

Phil
  • 157,677
  • 23
  • 242
  • 245
Waldir Bolanos
  • 422
  • 3
  • 7

1 Answers1

2

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
galymzhan
  • 5,505
  • 2
  • 29
  • 45
  • It's 2012. PHP has [anonymous functions](http://php.net/manual/en/functions.anonymous.php) now – Phil Jul 17 '12 at 05:24
  • @ Phil: my server is running on 5.2 :/ – Waldir Bolanos Jul 17 '12 at 05:29
  • @WaldirBolanos Do you always run six year old software on your servers? – Phil Jul 17 '12 at 06:06
  • No Phil, its a clients server (on godaddy.com) Nothing i can do about it, – Waldir Bolanos Jul 17 '12 at 19:51
  • Please note that this (create_function()) is depraced with PHP 7.2 and higher. For all version prior to PHP 7.2 it will performs an eval() which has the same security issues as eval(). Also it has bad performance and lot of memory usage. – Jerome Sep 16 '17 at 09:27