0

是否可以使用 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", $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,人名写道:”

$body = preg_replace('/(^\w.+:\n)?(^>.*(\n|$))+/mi', "", $body);
4

1 回答 1

0

这样做可能有一种更优雅的方式,但这应该可行(假设正则表达式是正确的):

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

编辑:正如 inhan 所指出的,电子邮件地址中的点(以及可能的其他特殊字符)需要preg_quote()在插入模式之前使用转义。

于 2012-07-31T03:23:04.947 回答