在PHP中获取尖括号之间和外部的文本

在PHP中获取尖括号之间和外部的文本,php,regex,pcre,Php,Regex,Pcre,我有以下格式的电子邮件地址: Jane Doe 我想将janedoe设置为一个变量和Jane。doe@example.com作为另一个 这是正则表达式的情况,还是有更优雅的方式 我能得到的最接近的表达式是/\,它返回(带尖括号)。您可以对字符串使用您的模式(或稍加修改的版本),并获得具有2个值的数组: $s = 'Jane Doe <jane.doe@example.com>'; $res = preg_split('/\s*<([^>]*)>/', $s, -1,

我有以下格式的电子邮件地址:

Jane Doe

我想将
janedoe
设置为一个变量和
Jane。doe@example.com
作为另一个

这是正则表达式的情况,还是有更优雅的方式

我能得到的最接近的表达式是
/\
,它返回
(带尖括号)。

您可以对字符串使用您的模式(或稍加修改的版本),并获得具有2个值的数组:

$s = 'Jane Doe <jane.doe@example.com>';
$res = preg_split('/\s*<([^>]*)>/', $s, -1, PREG_SPLIT_NO_EMPTY|PREG_SPLIT_DELIM_CAPTURE);
print_r($res); // => Array ( [0] => Jane Doe [1] => jane.doe@example.com )
请参阅和

图案细节

  • ^
    -字符串的开头
  • (?.*\S)
    -组“名称”:任何0+字符,直到最后一个非空白字符,后跟
  • \s*
    -0+空格字符
  • 位于字符串末尾

带有
preg\u split
列表
功能:

$input = 'Jane Doe <jane.doe@example.com>';

list($name, $email) = preg_split('/\s(?=<)/', $input);
$email = trim($email, '<>');
var_dump($name, $email);

使用捕获组,您可以与以下正则表达式匹配

正则表达式:
([^

说明:

<?php
   $line = "Jane Doe <jane.doe@example.com>";
   
   
   if (preg_match("/([^<]*)<([^>]*)>/", $line, $match)) :
      $name=$match[1];
      $email=$match[2];
      print "Name: ". $match[1];
      print "\nEmail Id: ". $match[2];
   endif;
?>
  • ([^]*)
    将捕获第二组中的电子邮件id

Php代码:

<?php
   $line = "Jane Doe <jane.doe@example.com>";
   
   
   if (preg_match("/([^<]*)<([^>]*)>/", $line, $match)) :
      $name=$match[1];
      $email=$match[2];
      print "Name: ". $match[1];
      print "\nEmail Id: ". $match[2];
   endif;
?>

输出

姓名:无名氏

电子邮件号码:jane。doe@example.com


请注意,您不需要使用惰性量词。
([^
也可以很好地工作(而且速度会快一点)@WiktorStribiżew:是的,我在用php编写代码时意识到了这一点。我将在regex演示中更正它。请注意,
不应转义。在某些regex风格中,
\
表示单词的开头,code\>表示单词的结尾。虽然php不是这样,但最好的做法是只转义必须转义的内容他逃走了。
<?php
   $line = "Jane Doe <jane.doe@example.com>";
   
   
   if (preg_match("/([^<]*)<([^>]*)>/", $line, $match)) :
      $name=$match[1];
      $email=$match[2];
      print "Name: ". $match[1];
      print "\nEmail Id: ". $match[2];
   endif;
?>