phpregexpreg-replaceregex-greedycharacter-class

Regex to match a curly braced placeholder is incorrectly matching multiple placeholders at once


I am having some problem with my regular expression in preg_replace() function. My code is as below.

$html = preg_replace("/{.*:C/", "func_call(", 'Hi Kevin. Your address is {Address:S111}. Your customer name is {Customer:C111}. Your customer id is {CustomerId:C1112}. You use laptop brand {Laptops:I4}. Thanks.');

print_r($html);

I am trying to replace {Customer:C111} by func_call(1111} and {CustomerId:C1112} by func_call(1112}. So I am expecting to get

Hi Kevin. Your address is {Address:S111}. Your customer name is func_call(1111}. Your customer id is func_call(1112}. You use laptop brand {Laptops:I4}. Thanks.

As you can see everything in the format {anything:Cnumber} will need to be replaced by func_call(number}

Currently am getting

Hi Kevin. Your address is func_call(1112}. You use laptop brand {Laptops:I4}. Thanks.


Solution

  • php > $str = 'Hi Kevin. Your address is {Address:S111}. Your customer name is {Customer:C111}. Your customer id is {CustomerId:C1112}. You use laptop brand {Laptops:I4}. Thanks.';
    php > echo preg_replace('#\{\w+:C(\d+)\}#', 'func_call(\\1)', $str);
    Hi Kevin. Your address is {Address:S111}. Your customer name is func_call(111). Your customer id is func_call(1112). You use laptop brand {Laptops:I4}. Thanks.