phpregexcallbackpreg-replaceuppercase

Make first letter of whitelisted words uppercase


I have this 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 I try doing the exact same thing with single quotes and with a function being used on $i it breaks,

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

Note the single quotes in the second parameter of the function, this now yields,

syntax error, unexpected '1' (T_LNUMBER), expecting variable (T_VARIABLE) or '{' or '$'

Live Example

Double Quotes

Single Quotes

So my question is why does this occur and how could I get the expected output (strong with ucfirst) as shown in the second example?

Update #1

This issue is happening not only because of the function ucfirst but due to the single quotes too as can be 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 '$'

Solution

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

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