根据数据类型替换指定字符包围的字符串

Replace string enclosed in specified characters based on data type

我需要替换 PHP 字符串中 <...> 中的字符。我用 preg_replace() 做了这个,但我需要修改这段代码来做更多的事情。

这是我的代码:

$templateText = "Hi <John> , This is a test message from <9876543210>";
$repl = "test";
$patt = "/\<([^\]]+)\>/"; 
echo $template_sample  = preg_replace($patt, $repl , $templateText);

以上代码会将 <...> 中第一次出现的值替换为 test

例如上面的代码将显示如下字符串:

Hi test

但是,只有当它不是数字时,我才需要用 test 替换它。如果包含的值为数字,则应将其替换为 999999999.

我期待的是:

Hi test , This is a test message from 999999999

您可以将 preg_replace_callback 与正则表达式一起使用,该正则表达式将匹配 <...> 之间 > 以外的任何数字或任何 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

参见PHP demo

图案详情

  • < - 文字 <(这不是特殊的正则表达式元字符,不要转义)
  • (?:(\d+)|[^>]*) - 匹配以下任一的非捕获组:
    • (\d+) - 第 1 组:一个或多个数字
    • | - 或
    • [^>]* - >
    • 以外的任何 0+ 个字符
  • > - 文字 >(这不是特殊的正则表达式元字符,请勿转义)。

替换是一个回调函数,它获取 $m 匹配对象并检查第 1 组是否匹配。如果第 1 组值不为空 (!empty($m[1])),则匹配替换为 999999999,否则替换为 test.