Php 我可以把代码缩短吗?
是否可以使用preg_replace而不是preg_match来缩短此代码 我用它来删除电子邮件正文中引用的文本。 当你回复邮件时引用某人的话Php 我可以把代码缩短吗?,php,preg-replace,preg-match,Php,Preg Replace,Preg Match,是否可以使用preg_replace而不是preg_match来缩短此代码 我用它来删除电子邮件正文中引用的文本。 当你回复邮件时引用某人的话 # Get rid of any quoted text in the email body # stripSignature removes signatures from the email # $body is the body of an email (All headers removed) $body_array = explode("\n"
# Get rid of any quoted text in the email body
# stripSignature removes signatures from the email
# $body is the body of an email (All headers removed)
$body_array = explode("\n", $this->stripSignature($body));
$new_body = "";
foreach($body_array as $key => $value)
{
# Remove hotmail sig
if($value == "_________________________________________________________________")
{
break;
# Original message quote
}
elseif(preg_match("/^-*(.*)Original Message(.*)-*/i",$value,$matches))
{
break;
# Check for date wrote string
}
elseif(preg_match("/^On(.*)wrote:(.*)/i",$value,$matches))
{
break;
# Check for From Name email section
}
elseif(preg_match("/^On(.*)$fromName(.*)/i",$value,$matches))
{
break;
# Check for To Name email section
}
elseif(preg_match("/^On(.*)$toName(.*)/i",$value,$matches))
{
break;
# Check for To Email email section
}
elseif(preg_match("/^(.*)$toEmail(.*)wrote:(.*)/i",$value,$matches))
{
break;
# Check for From Email email section
}
elseif(preg_match("/^(.*)$fromEmail(.*)wrote:(.*)/i",$value,$matches))
{
break;
# Check for quoted ">" section
}
elseif(preg_match("/^>(.*)/i",$value,$matches))
{
break;
# Check for date wrote string with dashes
}
elseif(preg_match("/^---(.*)On(.*)wrote:(.*)/i",$value,$matches))
{
break;
# Add line to body
}
else {
$new_body .= "$value\n";
}
}
这几乎奏效,但它保留了第一行“2012年7月30日星期一晚上10:54,人名写道:
可能有一种更优雅的方法可以做到这一点,但这应该是可行的(假设regexp是正确的):
编辑:正如inhan指出的,在插入模式之前,需要使用转义符对电子邮件地址中的点进行转义。注意电子邮件地址中的点。一旦变成正则表达式,它们可能会被解释为“任意字符”。@inhan:说得好。电子邮件地址可能应该转义以包含在正则表达式中。@Lèse majesté:尽管它更优雅,但不会使服务器工作更努力吗?@Draven:我不明白为什么它应该这样做。
$body = preg_replace('/(^\w.+:\n)?(^>.*(\n|$))+/mi', "", $body);
$search = array(
"/^-*.*Original Message.*-*/i",
"/^On.*wrote:.*/i",
"/^On.*$fromName.*/i",
"/^On.*$toName.*/i",
"/^.*$toEmail.*wrote:.*/i",
"/^.*$fromEmail.*wrote:.*/i",
"/^>.*/i",
"/^---.*On.*wrote:.*/i"
);
$body_array = explode("\n", $this->stripSignature($body));
$body = implode("\n", array_filter(preg_replace($search, '', $body_array)));
// or just
$body = str_replace(
array("\0\n", "\n\0"), '', preg_replace($search, "\0", $body)
);