【问题标题】:Replace string enclosed in specified characters based on data type根据数据类型替换包含在指定字符中的字符串
【发布时间】:2017-10-20 05:54:29
【问题描述】:

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

这是我的代码:

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

上面的代码会将&lt;...&gt; 中第一次出现的值替换为test。

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

Hi test

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

我期待的是:

Hi test , This is a test message from 999999999

【问题讨论】:

    标签: php regex string preg-replace


    【解决方案1】:

    您可以使用带有正则表达式的preg_replace_callback,该正则表达式将匹配&lt;...&gt; 之间的数字或除&gt; 之外的任何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。

    模式详情

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

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

    【讨论】:

    • 感谢 Wiktor,您的快速回复。它非常好。并感谢您的详细解释
    猜你喜欢
    • 2013-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-08
    • 1970-01-01
    • 1970-01-01
    • 2021-06-08
    相关资源
    最近更新 更多