正则表达式 - 我的PHP脚本中的preg_replace不起作用

时间:2016-09-19 15:16:29

标签: regex tinymce preg-replace

我有一个表单,我从TinyMCE编辑器中获取HTML代码作为我的textarea之一的输入来制作时事通讯。我想在每个链接的末尾添加utm代码。我模拟了一个RegEX模式并替换为在线编辑器,但保存的代码是通常的没有utm代码的href。

<?php
$subject=$_POST['subject'];
$from_email=$_POST['from_email'];
$from_name=$_POST['from_name'];
$replyto_email=$_POST['replyto_email'];
$replyto_name=$_POST['replyto_name'];
$lingua=$_POST['lingua'];
$body = mysqli_real_escape_string($db, $_POST['editor1']) ;

$string = $body;
$pattern = '/href="([^"]+)/';
$replacement = '$0?utm_source=newsletter&utm_medium=email&utm_campaign='.$subject;
$txt = preg_replace($pattern, $replacement, $string);

$stmt=null;
$stmt=$db->prepare("INSERT INTO newsletter_email(subject,from_email,from_name,replyto_email,replyto_name,lingua,body) VALUES('$subject','$from_email','$from_name','$replyto_email','$replyto_name','$lingua','$txt')");
if (!$stmt) {
  log_msg($db->error);
  die();
}
$stmt->execute();
$stmt->close();
$db->close();
?>

来自TinyMCE的$ body内容示例

$body = "<html><head></head><body><a href="example.com" target="_blank">Test</a></body></html>"

preg_replace之后的$ body内容示例

$body = "<html><head></head><body><a href="example.com?utm_source=newsletter&utm_medium=email&utm_campaign=Email Subject" target="_blank">Test</a></body></html>"

2 个答案:

答案 0 :(得分:1)

最简单的方法是使用$0代替$1进行替换:

$subject = 'Email subject';
$string = '<a href="example.com">';
$pattern = '/href="([^"]+)/';
$replacement = '$0?utm_source=newsletter&utm_medium=email&utm_campaign='.$subject;
$txt = preg_replace($pattern, $replacement, $string);

echo $txt;

<强>输出:

<a href="example.com?utm_source=newsletter&utm_medium=email&utm_campaign=Email subject">

答案 1 :(得分:0)

使用

  

mysqli_real_escape_string($ db,$ _POST ['editor1'])

它在标签之间添加'\',并且模式不匹配。它改变了(注意'。')

  

$ pattern ='/ href =。“([^”] +)/';