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 a开发者_如何学JAVAddress is func_call(1112}. You use laptop brand {Laptops:I4}. Thanks.
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.
Try
/{\w+:C/
As your regex. .*
is greedy, it will consume as much as it can.
This a very weird looking thing to do BTW.
You need to switch to the non-greedy version of *
.
Try this:
$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.');
$html = preg_replace("/\{([^:]+)\:([^\}]+)\}/", "func_call(\$2)", '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.');
"search for {
, followed by anything but :
, remember it in $1
, then match the first :
followed by anything but }
, remember it in $2. replace the while match with func_call($2)
if you wish you can do this without preg_replace something like this
$string ="Hi Kevin. Your address is %s. Your customer name is %s. Your customer id is %s. You use laptop brand %s. Thanks.'";
$string = sprintf($string,'{Address:S111}','{Customer:C111}','{CustomerId:C1112}','{Laptops:I4}');
精彩评论