0

I have the following preg_replace not preg_replace_callback which uses arrays for search patterns and replacement not only a single value and it works fine:

preg_replace(['/\{/','/\}/','/"(.*?)"/'],['<span class=\'olive\'>{','}</span>','<span class=\'olive\'>${0}</span>'],FoxText::insertBr($model->TafseerText));

However, when I try to pass ${0} to function something like:

preg_replace(['/\{/','/\}/','/"(.*?)"/'],['<span class=\'olive\'>{','}</span>',FoxText::pattern2VerseId("\$0")],FoxText::insertBr($model->TafseerText));

In the FoxText::pattern2VerseId function I try print_r as follows:

public static function pattern2VerseId($txt, $pattern = '/\(((\d+)-(\w+))\)/u')
 {
  $parts = array_map('trim',explode('-', $txt));
  print_r(explode('-', $parts[0]));
  return $parts[0].'  *'.$parts[0].'|';
 }

It prints Array ( [0] => $0 ) while the return value is matched string from the previous call!

In other words, how could it able to return $parts[0] as a string and It could not able to explode this string. Or how could I pass the value correctly to the function to be processed there?

By the way, the string is something like (125-Verse)

Community
  • 1
  • 1
SaidbakR
  • 13,303
  • 20
  • 101
  • 195
  • Possible duplicate of [Replace preg\_replace() e modifier with preg\_replace\_callback](http://stackoverflow.com/questions/15454220/replace-preg-replace-e-modifier-with-preg-replace-callback) – revo Oct 03 '16 at 15:44

2 Answers2

0

Because when you call the function pattern2VerseId you call it with the string $0. And since string $0 doesn't contain any hyphen, the explode just returns an array with single element containing the string.

explode('-', '$0') // will return Array([0] => $0)

By "\$0" are you actually trying to get the first part of the matched regex, i.e. 125 in this case? Because you're not doing it right.

mavili
  • 3,385
  • 4
  • 30
  • 46
  • what I mean by that is you think you're passing the matched part, but in fact you're just passing the string `$0`. – mavili Oct 04 '16 at 08:47
0

Since I have PHP < 7. i.e there is no preg_replace_callback_array, the only solution that I have able to use is replacing the first pattern(s) using preg_replace then passing the output to one preg_replace_callback

$p = preg_replace(['/\{/','/«/','/\(/','/\}/','/»/','/\)/','/"(.*?)"/'],['<span class=\'olive\'>{','<span class=\'olive\'>«','<span class=\'olive\'>(','}</span>','»</span>',')</span>','<span class=\'olive\'>${0}</span>'],FoxText::insertBr($model->TafseerText));
$callback = function($m){return FoxText::pattern2VerseId($m);}; 
echo preg_replace_callback('/\(((\d+)-(\w+))\)/u', $callback, $p);
SaidbakR
  • 13,303
  • 20
  • 101
  • 195