我在为邮寄书籍和杂志写求职信。我在数据库中有所有收件人的数据,我有PHP脚本获取这些数据并制作求职信。写求职信的用户,用特殊的字符来标记名字的位置等等。
例如,为了撰写一封求职信,用户写道:
亲爱的[last_name], 请找到附加的书..。
然后,它被PHP解析,[[last_name]]标记被替换为实名。当选择1000个地址供邮寄时,脚本生成1000个求职信,每个封信都有不同的名称。
现在,在我的俄语中,“亲爱的”一词对男性和女性有不同的结尾。就像我们在英语上说的“亲爱的先生。”或者“亲爱的夫人”
为了在求职信中标明这一点,用户为这个词写了可能的结尾:
亲爱的[欧/亚] [last_name]
也可以是这样的:
亲爱的.等。
我正在试图为我的PHP脚本找出正则表达式和替换命令来解析这类行。
对于我使用的last_name标记:
$text = ...//this is text of the cover letter with all the tags.
$res = $mysqli->query("SELECT * FROM `addresses` WHERE `flag` = 1")
while ($row=$res->fetch_assoc()) {
$text = str_replace('[[last_name]]', $row['lname'], $text);
echo $text;
}就我所知,结尾这个词应该是这样的:
$text = preg_replace('/\w{2-3}\//\w{2-3}/', ($row['gender']==1)
? 'regexp(first_half)'
: 'regext(second_half)', $text);我可以通过循环遍历标记、解析和替换来实现整个想法,但这将是5-10行代码。我确信这可以通过上面的线来完成,但我不知道如何做到。
发布于 2013-12-15 17:52:38
看http://www.phpliveregex.com/p/2BC,然后你用1美元的男性和2美元的女性.
preg_replace('~\[\[(.+?)/(.+?)\]\]~', $row['gender']==1?'$1':'$2', $text);发布于 2013-12-15 17:49:27
$gender = ($row['gender'] == 1) ? 1 : 2;
preg_replace_callback('#\[\[(?:([^\]/]+)(?:/([^\]/]+))?\]\]#',
function($match) use ($row, $gender) {
// $match will contain the current match info
// $match[1] will contain a field name, or the first part of a he/she pair
// $match[2] will be non-empty only in cases of he/she etc
return (empty($match[2])) ? $row[$match[1]] : $match[$gender];
}
);https://stackoverflow.com/questions/20597474
复制相似问题