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

Get text between and outside angle brackets in PHP

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

Jane Doe <jane.doe@example.com>

我想将 Jane Doe 设置为一个变量,将 jane.doe@example.com 设置为另一个变量。

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

我能得到的最接近的表达式是 /\<(.*?)\> 其中 returns <jane.doe@example.com>(带尖括号)。

您可以使用您的模式(或稍作修改的版本)preg_split 字符串并获得包含 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 )

PHP demo

\s*<([^>]*)> 模式找到 0+ 个空格 (\s*) 后跟 <,然后将 > 以外的任何 0+ 个字符捕获到第 1 组(使用 [^>]*) 然后匹配 >PREG_SPLIT_DELIM_CAPTURE 标志使 preg_split 将子匹配项(第 1 组值)保留在结果数组中。 PREG_SPLIT_NO_EMPTY 标志将丢弃任何可能出现在开头或结尾的空项目。 -1 limit 参数将 return 所有分割块(无限制)。

还有一个匹配的解决方案,我建议使用 命名捕获组:

$s = 'Jane Doe <jane.doe@example.com>';
if(preg_match('/^(?<name>.*\S)\s*<(?<email>.*)>$/', $s, $m)) {
  echo $m["name"] . "\n";
  echo $m["email"];
}

参见 this PHP demo and the regex demo

图案详情

  • ^ - 字符串开头
  • (?<name>.*\S) - 组 "name":任何 0+ 个字符,直到最后一个非空白字符后跟...
  • \s* - 0+ 个空白字符
  • < - 一个 < 字符
  • (?<email>.*) - 组 "email":任何 0+ 个字符,尽可能多到
  • >$ - > 在字符串末尾。

使用 preg_splitlist 函数:

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

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

输出:

string(8) "Jane Doe"
string(20) "jane.doe@example.com"

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

正则表达式: ([^<]*)<([^>]*)>

解释:

  • ([^<]*) 将捕获第 1 组中的名称。

  • ([^>]*) 将捕获第二组中的电子邮件 ID。

Regex101 Demo

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;
?>

输出

Name: Jane Doe

Email Id: jane.doe@example.com

Ideone Demo