php - preg_replace variable replacement showing error with single quotes -


i have preg_replace statement,

$s = "foo money bar"; echo preg_replace("/(office|rank|money)/i", "<strong>$1</strong>", $s); 

which returns,

foo <strong>money</strong> bar  

however when try doing exact same thing single quotes , function being used on $i breaks,

$s = "foo money bar"; echo preg_replace("/(office|rank|money)/i", '<strong>' . ucfirst($1) . '</strong>', $s); 

note single quotes in second parameter of function, yields,

syntax error, unexpected '1' (t_lnumber), expecting variable (t_variable) or '{' or '$' 

live example

double quotes

single quotes

so question why occur , how expected output (strong ucfirst) shown in second example?

update #1

this issue happening not because of function ucfirst due single quotes can seen in this example,

$s = "foo money bar"; echo preg_replace("/(office|rank|money)/i", '<strong>' . $1 . '</strong>', $s); 

output

syntax error, unexpected '1' (t_lnumber), expecting variable (t_variable) or '{' or '$' 

you can't use function in second parameter of preg_replace.
'<strong>' . ucfirst($1) . '</strong>' evaluated before search. use function in regex replacement, have use preg_replace_callback:

$result = preg_replace_callback($pattern, function ($m) {     return '<strong>' . ucfirst($m[1]) . '</strong>'; }, $yourstring); 

Comments

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -