问题描述
- 正则表达式替换{}请教
-
http://www.hao123.com/down.php?pid=4014&Id={a:0}&aaa={b:222}请教这种正则怎么替换?
{a:0}替换成1,{b:222}替换成2
解决方案
$url="http://www.hao123.com/down.php?pid=4014&Id={kk:0}&aaa={b:222}";
$arr=array(
'kk'=>1,
'b' =>2,
'c' => 3,
);
foreach ($arr as $k => $value) {
if(strstr("$url","$k:")){
$url=preg_replace("/\{".$k.":\d+\}/",$value,$url);
}
}
echo $url;
js
'http://www.hao123.com/down.php?pid=4014&Id={a:0}&aaa={b:222}'.replace(/{a:0}/,'1').replace(/{b:222}/,'2')
解决方案三:
如果a,b都是变量呢?
$url="http://www.hao123.com/down.php?pid=4014&Id={kk:0}&aaa={b:222}";
$arr=array(
'kk'=>1,
'b' =>2,
'c' => 3,
);
foreach ($arr as $k => $value) {
if(strstr("$url","$k")){
$url=preg_replace("/{.*?:.*?}/",$value,$url);
}
}
echo $url;
这样的话,都替换成一个了,http://www.hao123.com/down.php?pid=4014&Id=1&aaa=1,显然是错的,
应该是:http://www.hao123.com/down.php?pid=4014&Id=1&aaa=2;
时间: 2024-10-29 12:19:48