Php 根据数据类型替换包含在指定字符中的字符串
我需要在PHP字符串中替换Php 根据数据类型替换包含在指定字符中的字符串,php,regex,string,preg-replace,Php,Regex,String,Preg Replace,我需要在PHP字符串中替换中包含的字符。我使用了preg\u replace(),但是我需要修改这段代码来做更多的工作 这是我的密码: $templateText = "Hi <John> , This is a test message from <9876543210>"; $repl = "test"; $patt = "/\<([^\]]+)\>/"; echo $template_sample = preg_replace($patt, $rep
中包含的字符。我使用了preg\u replace()
,但是我需要修改这段代码来做更多的工作
这是我的密码:
$templateText = "Hi <John> , This is a test message from <9876543210>";
$repl = "test";
$patt = "/\<([^\]]+)\>/";
echo $template_sample = preg_replace($patt, $repl , $templateText);
但是,只有当它不是数字时,我才需要将其替换为test
。如果所附数值为数字,则应将其替换为99999999
我期待的是:
Hi test , This is a test message from 999999999
您可以使用带有正则表达式的
preg\u replace\u回调
,该正则表达式将匹配
之间的数字或任何0+字符,而不是
,并使用自定义逻辑进行替换:
$templateText = "Hi <John> , This is a test message from <9876543210>";
$template_sample = preg_replace_callback("/<(?:(\d+)|[^>]*)>/", function($m) {
return !empty($m[1]) ? '999999999' : 'test';
}, $templateText);
echo $template_sample; // => Hi test , This is a test message from 999999999
$templateText=“您好,这是来自”的测试消息”;
$template\u sample=preg\u replace\u回调(“/]*)>/”,函数($m){
return!空($m[1])?'99999999':'test';
},$templateText);
echo$template_sample;//=>您好,测试,这是来自99999999的测试消息
看
图案细节
-除]*
以外的任何0+字符
-文字
(这不是特殊的正则表达式元字符,请勿转义)替换是一个回调函数,它获取
$m
匹配对象并检查组1是否匹配。如果组1的值不为空(!empty($m[1])
),则匹配项将替换为9999999
,否则替换为test
,谢谢您的快速响应。很好。谢谢你的详细解释
$templateText = "Hi <John> , This is a test message from <9876543210>";
$template_sample = preg_replace_callback("/<(?:(\d+)|[^>]*)>/", function($m) {
return !empty($m[1]) ? '999999999' : 'test';
}, $templateText);
echo $template_sample; // => Hi test , This is a test message from 999999999