我有一个我正在解析的文件而我正在尝试用$mail["email_from"] = "test@example.com";
替换$mail["email_from"] = request("email");
,(这意味着我想要替换$mail["email_from"]
处的所有行。最后开始;
)这里是我的preg_replace:
$email = "$mail[\"email_from\"] = request(\"email\")";
$newcontent = preg_replace("/\$mail[\"email_from\"](.+);/",$email,$content);
我的代码中出现了什么错误?以及如何解决它?非常感谢
答案 0 :(得分:1)
$email = "$mail[\"email_from\"] = request(\"email\")";
^---double-quoted string
^^^^^---array reference
您可能需要
$email = "\$mail[\"email_from\"] = request(\"email\")";
^--escape the $
答案 1 :(得分:1)
使用好的引号并转义所需的所有字符后,这可以工作:
$email = '$mail["email_from"] = "test@example.com";';
$replacement = '$mail["email_from"] = request("email");';
$newContent = preg_replace('/\\$mail\\[\\"email_from\\"\\](.+);/i', $replacement, $email);
echo $newContent; //$mail["email_from"] = request("email");
答案 2 :(得分:1)
使用^
和$
指定行的开头和结尾。需要转发$
,[
和]
等特殊字符。
<?php
$content = '$mail["email_from"] = "test@example.com";';
$email = '$mail["email_from"] = request("email");';
$newcontent = preg_replace('/^\$mail\["email_from"\] =.+;$/',$email,$content);
echo $newcontent . "\n";
输出:
$mail["email_from"] = request("email");