【问题标题】:PHP fast way to replace content within string between charactersPHP快速方法来替换字符之间的字符串中的内容
【发布时间】:2012-07-30 15:36:29
【问题描述】:

在创建自动电子邮件时,需要将电子邮件的某些部分替换为存储的数据。

例如。亲爱的%first_name% %surname%,感谢您参加%place_name%

这可以通过对它们中的每一个进行字符串替换来完成,但必须有更快的方法。

假设变量名称与我们想要的系统名称相同,例如。 %first_name% 应替换为 $user['first_name'] 等......

【问题讨论】:

    标签: php variables str-replace


    【解决方案1】:

    您可以利用preg_replace_callback% 之间的键替换为数组值:

    $fields = array('first_name' => 'Tim', 'place_name' => 'Canada');
    
    $string = preg_replace_callback('/%(.+?)%/', function($arr) use($fields)
    {
        $key = $arr[1];
        return array_key_exists($key, $fields) ? $fields[$key] : $arr[0];
    }, $string);
    

    【讨论】:

    • 巧妙使用闭包,需要较新版本的PHP
    • @Kristian: PHP 5.3,引入匿名函数语法的版本,3 年前发布。我不会认为它更新,我希望每个人都至少升级到那个版本。
    • 永远不要低估代码/版本要求的力量,以强制减缓升级的发生
    【解决方案2】:

    一个选项:

    $vars = array(
      'firstname' = 'Bob',
      'surname' = 'Dole',
      'place' = 'Las Vegas',
      // ...
    );
    extract($vars);
    include('my_template.phtml');
    

    在 my_template.phtml 中:

    <?php
    echo <<<EOF
        Dear $firstname $surname,<br>
        Thank you for attending the Viagra and Plantains Expo in $place.
    EOF;
    ?>
    

    如果您在使用 extract() 时担心名称冲突,您可以随时使用 EXTR_PREFIX_ALL 选项或其他提取方法之一。

    或者,更好的是,不要重新发明轮子。只需使用Smartymustache.php

    另请参阅此问题:PHP template class with variables?

    【讨论】:

    • +1 这是我输出视图的方法,我推荐它
    • @Kristian:是的,CakePHP 和可能许多其他框架/库都是这样做的,尽管通常具有输出缓冲等附加功能,并且在 Cake 2.0 中,视图块和视图继承。跨度>
    猜你喜欢
    • 2017-07-18
    • 1970-01-01
    • 2016-05-08
    • 1970-01-01
    • 1970-01-01
    • 2016-11-14
    • 1970-01-01
    • 1970-01-01
    • 2014-12-13
    相关资源
    最近更新 更多