制作一行正则表达式

时间:2013-12-15 17:25:06

标签: php regex preg-replace

我正在为邮寄书籍和杂志写封面信。我拥有数据库中的所有收件人数据,我有PHP脚本获取该数据并制作求职信。使用特殊字符书写该求职信以标记应放置姓名的用户等。

例如,为了撰写求职信,用户写道:

  

亲爱的[[last_name]],

     

请找附件......

然后它被PHP脚本解析,[[last_name]]标记被实名替换。当选择1000个地址进行邮寄​​时,该脚本会生成1000个求职信,每个求职信都有不同的名称。

现在,用我的俄语单词“Dear”对男性和女性有不同的结局。就像我们对英语“亲爱的先生”说的那样。或者“亲爱的夫人。”

为了在求职信中标记用户,请写下该词的可能结尾:

  

亲爱的[[oy / aya]] [[last_name]]

或者它可能是这样的:

  

亲爱的[[ie / oe]] ......等等。

我正在尝试找出我的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行代码。我确信这可以通过上面的行完成,但我无法弄清楚如何。

2 个答案:

答案 0 :(得分:2)

$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];
    }
);

答案 1 :(得分:2)

请参阅http://www.phpliveregex.com/p/2BC,然后替换为男性为1美元,女性为2美元 ......

preg_replace('~\[\[(.+?)/(.+?)\]\]~', $row['gender']==1?'$1':'$2', $text);