我可以缩短这段代码吗?

时间:2012-07-31 03:07:01

标签: 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", $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";
    }
}

这几乎有效,但它保留了第一行“On Mon,Jul 30,2012 at 10:54 PM,Persons Name写道:”

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

1 个答案:

答案 0 :(得分: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)
);

修改:正如指出的那样,在插入模式之前,需要使用other special characters对电子邮件地址中的点(以及可能的preg_quote())进行转义。