1

我确实有一个这样的变量:

$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]?

谢谢你。

4

3 回答 3

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*)?可选匹配所有不是 a 的内容,<并且除了尾随空格之外的所有内容都存储在组 1 中。

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

于 2012-05-02T11:08:17.160 回答
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;
于 2012-05-02T10:49:38.297 回答
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 “&lt;” literally «<»
Match the regular expression below and capture its match into backreference number 2 «([^<>"]+)»
   Match a single character NOT present in the list “&lt;>"” «[^<>"]+»
      Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
Match the character “&gt;” 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);

于 2012-05-02T10:49:55.597 回答