【问题标题】:preg_replace and big brackets {} [closed]preg_replace 和大括号 {} [关闭]
【发布时间】:2016-07-18 12:17:12
【问题描述】:

我想制作一个电子邮件模板,如何将括号{}中的所有内容替换为括号{}

$template = "My name is {NAME}. I'm {AGE} years old.";
$template = preg_replace("{NAME}", "Tom", $template);
$template = preg_replace("{AGE}", "10", $template);

之后应该是这样的: 我的名字是汤姆。我今年 10 岁。

【问题讨论】:

标签: php


【解决方案1】:

使用str_replace 代替preg_replace

$template = "My name is {NAME}. I'm {AGE} years old.";
$template = str_replace("{NAME}", "Tom", $template);
$template = str_replace("{AGE}", "10", $template);

【讨论】:

    【解决方案2】:

    您可以将preg_replace() 与下面的单行一起使用(优于str_replace()):-

    $template = "My name is {NAME}. I'm {AGE} years old.";
    $find = array('/{NAME}/', '/{AGE}/');
    $replace = array('TOM', '10');
    $template = preg_replace($find, $replace, $template);
    
    echo $template;
    

    输出:- https://eval.in/606528

    注意:- 它有以下好处:-

    1。单行代码替换所有你想要的。一次又一次不需要str_replace()

    2。如果将来需要更多替换,那么您必须将它们添加到 $find$replace 中,仅此而已。所以更灵活。

    对不起,我完全忘了提到 str_replace() 也可以与数组一起使用,所以你也可以像下面这样:-

    <?php
    
    $template = "My name is {NAME}. I'm {AGE} years old.";
    $find = array('{NAME}', '{AGE}');
    $replace = array('TOM', '10');
    $template = str_replace($find, $replace, $template);
    
    echo $template;
    

    输出:-https://eval.in/606577

    注意:- 两者都一样好。你可以去任何一个。谢谢

    【讨论】:

    • 擒纵机构呢?大括号不是正则表达式中的保留字符吗?
    • @RamenChef 没有 php 正则表达式的工作方式不同
    • 我喜欢数组的方式,但为什么不用 str_replace() 替换 preg_replace() 函数,它可以很好地处理数组?我以前没有考虑过 str_replace ,在我的情况下它似乎更好。
    【解决方案3】:

    正则表达式模式的开头和结尾应该有分隔符

    $template = "My name is {NAME}. I'm {AGE} years old.";
    $template = preg_replace("/{NAME}/", "Tom", $template);
    echo $template = preg_replace("/{AGE}/", "10", $template);
    

    【讨论】:

      【解决方案4】:

      preg_replace 不是在这种情况下使用的正确函数。在这种情况下,正确的选项是str_replacestr_ireplace。但是,对于要格式化的大量数据,使用正则表达式会更好:

      $associative_formatter_array = array('NAME' => 'Tom', "AGE" => '10');
      $template = "My name is {NAME}. I'm {AGE} years old.";
      $template = preg_replace_callback("`\{([^\}]*)\}`g", function($match) {
        return $_GLOBALS["associative_formatter_array"][$match[1]];
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-11-13
        • 1970-01-01
        • 2018-12-03
        • 2012-02-25
        • 2010-11-04
        • 2020-12-28
        • 2011-09-10
        相关资源
        最近更新 更多