如何在 php 正则表达式中捕获可选词
How to capture optional word in php regex
内容结构如下:
$contents = '1234 FIRSTNAME LASTNAME M 4321
1345 LASTNAME F 4621
8223 FIRSTNAME LASTNAME M 4256;
我只想提取数组中的名字或姓氏,如下所示:
Array ( [0] => FIRSTNAME LASTNAME,
[1] => LASTNAME )
我的代码:
<?php
$contents = '1234 FIRSTNAME LASTNAME M 4321
1345 LASTNAME F 4621
8223 FIRSTNAME LASTNAME M 4256';
$res = preg_replace('/([A-Z]{2,24})\s+([A-Z]{2,24})/', ' ', $contents);
preg_match_all('/([A-Z]{2,24}?\s[A-Z]{2,24})/', $res, $result);
print_r($result[1]);
您可以将以下正则表达式与仅 preg_match_all
函数一起使用:
'~\b[A-Z]{2,}(?:\h+[A-Z]{2,})?\b~'
参见regex demo。
详情
\b
- 单词边界
[A-Z]{2,}
- 2 个或更多大写 ASCII 字母(替换为 \p{Lu}
并使用 u
修饰符匹配所有 Unicode 大写字母
(?:\h+[A-Z]{2,})?
- 一个可选的序列
\h+
- 1+ 个水平空格(似乎姓氏和名字总是在一行上)
[A-Z]{2,}
- 2 个或更多大写 ASCII 字母
\b
- 单词边界。
参见 PHP demo:
$contents = '1234 FIRSTNAME LASTNAME M 4321
1345 LASTNAME F 4621
8223 FIRSTNAME LASTNAME M 4256';
if (preg_match_all('/\b[A-Z]{2,}(?:\h+[A-Z]{2,})?\b/', $contents, $result)) {
print_r($result[0]);
}
输出:
Array
(
[0] => FIRSTNAME LASTNAME
[1] => LASTNAME
[2] => FIRSTNAME LASTNAME
)
内容结构如下:
$contents = '1234 FIRSTNAME LASTNAME M 4321
1345 LASTNAME F 4621
8223 FIRSTNAME LASTNAME M 4256;
我只想提取数组中的名字或姓氏,如下所示:
Array ( [0] => FIRSTNAME LASTNAME,
[1] => LASTNAME )
我的代码:
<?php
$contents = '1234 FIRSTNAME LASTNAME M 4321
1345 LASTNAME F 4621
8223 FIRSTNAME LASTNAME M 4256';
$res = preg_replace('/([A-Z]{2,24})\s+([A-Z]{2,24})/', ' ', $contents);
preg_match_all('/([A-Z]{2,24}?\s[A-Z]{2,24})/', $res, $result);
print_r($result[1]);
您可以将以下正则表达式与仅 preg_match_all
函数一起使用:
'~\b[A-Z]{2,}(?:\h+[A-Z]{2,})?\b~'
参见regex demo。
详情
\b
- 单词边界[A-Z]{2,}
- 2 个或更多大写 ASCII 字母(替换为\p{Lu}
并使用u
修饰符匹配所有 Unicode 大写字母(?:\h+[A-Z]{2,})?
- 一个可选的序列\h+
- 1+ 个水平空格(似乎姓氏和名字总是在一行上)[A-Z]{2,}
- 2 个或更多大写 ASCII 字母
\b
- 单词边界。
参见 PHP demo:
$contents = '1234 FIRSTNAME LASTNAME M 4321
1345 LASTNAME F 4621
8223 FIRSTNAME LASTNAME M 4256';
if (preg_match_all('/\b[A-Z]{2,}(?:\h+[A-Z]{2,})?\b/', $contents, $result)) {
print_r($result[0]);
}
输出:
Array
(
[0] => FIRSTNAME LASTNAME
[1] => LASTNAME
[2] => FIRSTNAME LASTNAME
)