正则替换中 用$1,$2...去获取匹配到的部分字符串,我要把 $1,$2...当做别的函数的参数,怎么办。
我的代码如下:$str="hello ,my email is [email] ,keep in contact!!"; //我要用正则匹配出[email],并把它替换成email的字符长度,即5,
也就是说替换完后应该变为hello ,my email is 5 ,keep in contact!!$str1=preg_replace('/\[(\w+)\]/',strlen('$1'),$str);
echo $str1;//输出的却是hello ,my email is 2 ,keep in contact!!
也就是说它把'$1'当然字符串来传递了,但是我试了把strlen('$1')换成strlen($1)又会出错,用eval()去修改它也不行请大侠们给看看 ~~
我的代码如下:$str="hello ,my email is [email] ,keep in contact!!"; //我要用正则匹配出[email],并把它替换成email的字符长度,即5,
也就是说替换完后应该变为hello ,my email is 5 ,keep in contact!!$str1=preg_replace('/\[(\w+)\]/',strlen('$1'),$str);
echo $str1;//输出的却是hello ,my email is 2 ,keep in contact!!
也就是说它把'$1'当然字符串来传递了,但是我试了把strlen('$1')换成strlen($1)又会出错,用eval()去修改它也不行请大侠们给看看 ~~
<?php
// 此文本是用于 2002 年的,
// 现在想使其能用于 2003 年
$text = "April fools day is 04/01/2002\n";
$text.= "Last christmas was 12/24/2001\n"; // 回调函数
function next_year($matches) {
// 通常:$matches[0] 是完整的匹配项
// $matches[1] 是第一个括号中的子模式的匹配项
// 以此类推
return $matches[1].($matches[2]+1);
} echo preg_replace_callback(
"|(\d{2}/\d{2}/)(\d{4})|",
"next_year",
$text); // 结果为:
// April fools day is 04/01/2003
// Last christmas was 12/24/2002
?>
echo preg_replace('/\[(\w+)\]/e',"strlen('$1')",$str);
function foo($r) {
return strlen($r[1]);
}
echo preg_replace_callback('/\[(\w+)\]/',"foo",$str);
请教xuzuning:$data=array{'email'=>'[email protected]','user_name'=>'ddanfg'};
$message="hello [user_name],your email is [email]";
echo preg_replace('/\[(\w+)\]/e',"$data['$1']",$message);
//我是输出hello ddanfg,your email is [email protected]
便是却提示出错, 请问这种的参数当数组下标的要怎样写?
用3楼的方法弄一个函数,你的数组写错了,应该是array(),不是中括号
方法如下:function foo($r) {
global $data;
return $data[$r];
}
$data=array('email'=>'[email protected]','user_name'=>'ddanfg');
$message="hello [user_name],your email is [email]";
echo preg_replace('/\[(\w+)\]/e',"foo('$1')",$message);
$message="hello [user_name],your email is [email]";
echo preg_replace('/\[(\w+)\]/e', '$data[$1]',$message);
这样它会提示出错parse error, unexpected '[' in ………………
我两个地方测试都正常显示啊(php5.2.9,5.2.10):hello ddanfg,your email is [email protected]
echopreg_replace里得到的是foo('$1')的返回字符串值