PHP快速替换字符串中字符间内容的方法


PHP fast way to replace content within string between characters

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

例如。尊敬的%first_name% %surname%,感谢您参加%place_name%

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

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

您可以使用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);

一个选项:

$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选项或其他提取方法之一。

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

另请参阅以下问题:带有变量的PHP模板类?