Using function in the function preg_replace

Hi
I have a problem, I have two functions tagi() and ObrobkaTekstu. I have not idea how using function tagi in preg_replace in function ObrobkaTekstu().

function tagi($x)
{
  $x=str_replace('<','<',$x);
  $x=str_replace('>','>',$x);
  return $x;
}

function ObrobkaTekstu($tekst_do_obrobki)
{
  $tekst_do_obrobki=preg_replace('{\\[code\\](.*?)\\[/code\\]}s','<pre>$1</pre>',$tekst_do_obrobki);
  //....
  return $tekst_do_obrobki;
}

I tried this:

$tekst_do_obrobki=preg_replace('{\\[code\\](.*?)\\[/code\\]}s','<pre>'.tagi('$1').'</pre>',$tekst_do_obrobki);

of course this code dosnt work.

Who has idea?

Hi there,

And welcome to the forums.

the problem with your code is that you cannot pass $1 as a parameter to a function like this, as it would be called before preg_replace is executed.
In this case, you can use preg_replace_callback

This will do what you want:

function tagi($x){
  $x[1]=str_replace('<','<',$x[1]);
  $x[1]=str_replace('>','>',$x[1]);
  return "<pre>$x[1]</pre>";
}

function ObrobkaTekstu($tekst_do_obrobki){
  return preg_replace_callback('{\\[code\\](.*?)\\[/code\\]}s', "tagi", $tekst_do_obrobki);
}

$tekst_do_obrobki = "

<hello>SitepointRocks!<goodbye>

";
echo ObrobkaTekstu($tekst_do_obrobki);
?>

This will output:

<pre><hello>SitepointRocks!<goodbye></pre>

I hope that helps you.

Thank you for your help! That’s it.