将字符串分为ucword和小写的2个数组

时间:2019-01-09 18:34:06

标签: php regex

我有几个句子,其中包括人名(或只是姓氏)和字符串的其余部分。我试图将他们分开作为人的名字和其余的名字。 (句子总是以名字开头)

$string = "John Doe loves to eat apples";

$string = "John loves likes to run";

$string = "John Mike Doe loves to swim";

$string = "Greg McDermott lives in Sydney"; // this from comments is a good scenario.

我的数组结果应该是

[ "John Doe", 'loves to eat apples" ]
[ "John", 'likes to run" ]
[ "John Mike Doe", 'loves to swim" ]

我用preg_match_all()取得了一些成就,但是我想知道是否有更直接的方法来实现它。

$string = "John Doe loves to eat apples";
preg_match_all('/((?:^|[A-Z])[a-z]+)/', $string, $matches);
$person = implode(' ', $matches[0]);
$rest = str_replace("$person ", '', $string);

1 个答案:

答案 0 :(得分:1)

您可以使用此正则表达式捕获字符串开头的名称,该名称的标识是每个名字或姓氏均以大写字母开头。

^[A-Z][A-Za-z]+\b(?: \b[A-Z][A-Za-z]+\b)*

说明:

  • ^-字符串的开头
  • \b[A-Z][A-Za-z]+\b-捕获名称,该名称应以大写字母开头。 \b确保不进行部分匹配。
  • (?: \b[A-Z][A-Za-z]+\b)*-这可以容纳名字零次或多次出现的其他姓氏。

Demo