php - preg_replace / backreference - 从邮件地址中提取部件的语法

时间:2012-05-02 10:41:00

标签: php regex preg-replace preg-match

我确实有这样的var:

$mail_from = "Firstname Lastname <email@domain.com>";

我想收到

array(name=>"firstname lastname", email=>"email@domain.com")
or 
the values in two separate vars ($name = "...", $email = "...")

我一直在玩preg_replace,但不知何故不完成它......

进行了广泛的搜索,但没有找到办法完成这项工作。

这是我最接近的:

$str = 'My First Name <email@domain.com>';
preg_match('~(?:"([^"]*)")?\s*(.*)~',$str,$var);
print_r($var);
echo "<br>Name: ".$var[0];
echo "<br>Mail: ".$var[2];

如何将“email@domain.com”输入$ var ['x]?

谢谢。

3 个答案:

答案 0 :(得分:2)

这适用于您的示例,并且应该始终有效,当电子邮件位于尖括号内时。

$str = 'My First Name <email@domain.com>';
preg_match('~(?:([^<]*?)\s*)?<(.*)>~', $str, $var);
print_r($var);
echo "<br>Name: ".$var[1];
echo "<br>Mail: ".$var[2];

<强>解释

(?:([^<]*?)\s*)?可选地匹配非<的所有内容,除了尾随空格之外的所有内容都存储在第1组中。

<(.*)>匹配尖括号之间的内容并将其存储在第2组中。

答案 1 :(得分:0)

 //trythis
 $mail_from = "Firstname Lastname <email@domain.com>";
 $a = explode("<", $mail_from);
 $b=str_replace(">","",$a[1]);
 $c=$a[0];
 echo $b;
 echo $c;

答案 2 :(得分:0)

试试这个:

(?<=")([^"<>]+?) *<([^<>"]+)>(?=")

<强>解释

<!--
(?<=")([^"<>]+?) *<([^<>"]+)>(?=")

Options: ^ and $ match at line breaks

Assert that the regex below can be matched, with the match ending at this position (positive lookbehind) «(?<=")»
   Match the character “"” literally «"»
Match the regular expression below and capture its match into backreference number 1 «([^"<>]+?)»
   Match a single character NOT present in the list “"<>” «[^"<>]+?»
      Between one and unlimited times, as few times as possible, expanding as needed (lazy) «+?»
Match the character “ ” literally « *»
   Between zero and unlimited times, as many times as possible, giving back as needed (greedy) «*»
Match the character “<” literally «<»
Match the regular expression below and capture its match into backreference number 2 «([^<>"]+)»
   Match a single character NOT present in the list “<>"” «[^<>"]+»
      Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
Match the character “>” literally «>»
Assert that the regex below can be matched, starting at this position (positive lookahead) «(?=")»
   Match the character “"” literally «"»
-->

代码:

$result = preg_replace('/(?<=")([^"<>]+?) *<([^<>"]+)>(?=")/m', '<br>Name:$1<br>Mail:$2', $subject);