How to replace c (xxx) with c (xxx) in preg_replace?

How to replace c(xxx) with c(xxx) in preg_replace ?

In the code below, I want to replace str c(xxx) with functioun c(xxx) .
I cannot get the correct result that I want.
What is wrong with my code? and how to fix it?

 $c['GOOD']='very good'; $c['BOY']='jimmy'; function c($x){ global $c; if(isset($c[$x])){ return $c[$x]; } } $str="hello c(GOOD) world c(BOY) "; $str=preg_replace("@c\(([A-Z_\d]+)\)@",c('$1'),$str); echo $str; // --> hello world // how to get hello very good world jimmy 
+4
source share
3 answers

Try the e modifier http://php.net/manual/en/reference.pcre.pattern.modifiers.php

Note. . This feature has been disabled since PHP 5.5.0. Based on this feature, it is highly discouraged.

 <?php $str = preg_replace( "/c\(([A-Z_\d]+)\)/e", 'c("$1")', $str ); ?> 

Better to use preg_replace_callback

 <?php $str = preg_replace_callback( "/c\(([A-Z_\d]+)\)/", function( $m ) { return c( $m[1] ); }, $str ); ?> 
+2
source

php.net: preg_replace_callback ()

If you look at example # 2, this is what you are looking for :)

 function c($matches){ print_r($matches) } $str = preg_replace_callback("@c\(([A-Z_\d]+)\)@", 'c', $str); 

A small side kernel: I don’t know if you want to name your function 'c', but I offer clear functional names that explain what they do

+3
source

you can use preg_replace_callback with anonymous functions

 <?php $c['GOOD']='very good'; $c['BOY']='jimmy'; $str="hello c(GOOD) world c(BOY) "; echo preg_replace_callback('@c\((.*?)\)@', function ($match) use ($c) { if (isset($c[$match[1]])) return $c[$match[1]]; }, $str); ?> 

The advantage of this function is this: it allows you to pass the second parameter, see use ($c) . Then there is no need to create a second function.

0
source

Source: https://habr.com/ru/post/1493390/


All Articles