2013-01-24 43 views
1

我有一个变量,包含“占位符”,一旦运行就应该用db数据替换。这是为了制作通用电子邮件。Php,拉出占位符变量

下面是变量的一个示例:

$emailBody = "Dear [-first_name-] [-last_name-]"; 

我然后将要求first_name的&姓氏db和用适当的值替换那些占位符。

现在我的最终目标是要找到这些关键条款,把它们变成:

$emailBody = "Dear John Smith"; 

所以我想我需要一种方法来值爆炸成一个数组,寻找[ - - ]然后做修复然后使$ emailBody等于修改后的变量。我只是很难找出如何寻找每一组[ - - ]。

+0

我并不总是提取并更换占位一个字符串,但是当我喜欢'preg_replace_callback()' –

回答

2

你可以这样做:

$emailBody = "Dear [-first_name-] [-last_name-]"; 

$tokens = array("[-first_name-]", "[-last_name-]"); 
$replacements = array("John", "Doe"); 
$emailBody = str_replace($tokens, $replacements, $emailBody); 
+0

不要运行循环。只要匹配和替换数组排队,str_replace就可以在数组上运行。 http://us3.php.net/manual/en/function.str-replace.php#example-4697 – thinice

+0

@thinice感谢您的改进 –

0

这是我通常处理邮件合并。它使用正则表达式来查找由[--]包围的所有字符串,然后对它可以找到的匹配执行替换。

str_replace()strtr()解决方案不同的是,它可以让你找到任何模式满足[-xxx-],不只是你期望的人。但是,您可以处理条件你喜欢:

$user = new stdClass; // this may well be an array 
$user->first_name = 'Jack'; 
$user->last_name = 'Jackson'; 

echo preg_replace_callback('/\[-([a-z_]*)-\]/', function($match) use ($user) { 
    $field = $match[1]; 
    if (isset($user->$field)) { 
     return $user->$field; 
    } 
    // the field was not present, decide what to do 
    return ''; // or: return $match[0]; 
}, $emailBody); 

参见:preg_replace_callback()


类似的答案,我已经给前:

How to include shortcodes into php email template

Fastest way to replace string patterns by mask

-1

我猜测你是否在使用a标准模板与每次相同的地方持有人,您可以使用一个简单的str_replace为您要替换的每个占位符。

另外,你可以抓住字段列表,然后遍历它。

喜欢的东西:

$mysqli = new mysqli("localhost", "my_user", "my_password", "world"); 

$result = $mysqli->query("SELECT first_name, last_name FROM table WHERE id=$id"); 

$fieldList = $result->fetch_fields($result); 
$row = $mysqli->fetch_assoc(); 

foreach($fieldList as $field) { 
    $fieldName = $field->name 
    $email_body = str_replace("[-$fieldName-]", $row[$fieldName], $email_body); 
} 
1

可以使用str_replace function

$emailBody = 'Dear [-first_name-] [-last_name-]'; 

$search = array('[-first_name-]', '[-last_name-]'); 
$replace = array('John', 'Smith'); 

$emailBody = str_replace($search, $replace, $emailBody); 

会离开$ emailBody为 “亲爱的约翰史密斯”