【问题标题】:regex - preg_replace in my PHP script doesn't work正则表达式 - 我的 PHP 脚本中的 preg_replace 不起作用
【发布时间】:2016-09-19 15:16:29
【问题描述】:

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

<?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>"

【问题讨论】:

  • 在询问 RegEx 问题时,始终欢迎明确的易于捕捉的输入和预期输出对。
  • 你是对的。这里:&lt;a href="example.com"&gt; --> &lt;a href="example.com?utm_source=newsletter&amp;utm_medium=email&amp;utm_campaign=Email subject"&gt;
  • 您的替换字符串不完整。应该是$replacement = 'href="$1?utm_source=newsletter&amp;utm_medium=email&amp;utm_campaign='.$subject;
  • @revo 和之前一样的问题 :(
  • 你得到什么输出?

标签: regex tinymce preg-replace


【解决方案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">

【讨论】:

  • OP 有一个问题,可能会覆盖之前的任何更改。我认为他不使用正确的变量,否则他的问题应该由 cmets 解决。
  • 当我把一些东西放在 $string 变量中作为例子时它可以工作,但当 $string 以这种方式从 TinyMCE 编辑器获取 $body 的内容时不起作用:$body = mysqli_real_escape_string($db, $_POST['editor1']) ; $body 包含多个包含整个 HTML 的行,例如:&lt;html&gt;&lt;head&gt;&lt;/head&gt;&lt;body&gt;&lt;a href="example.com"&gt;&lt;/body&gt;&lt;/html&gt; 抱歉,我不清楚。
  • @Otto:即使在整个 html 页面中它也适用于我,链接会根据要求更改。请使用完整的可复制示例和您想要的输出来编辑您的问题。
【解决方案2】:

使用

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

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

$pattern = '/href=."([^"]+)/';

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-05-20
    • 2023-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多