使用手术室时遇到问题 |PHP preg_match 中的运算符


Trouble Using the OR | operator in PHP preg_match

使用以下字符串,这些字符串通过UI生成,但显示两次以显示可能的变体;

$string = 'The quick brown fox jumped over the LE300 tractor';

$string = 'The quick brown fox jumped over the LE 300 tractor';

$string = 'The quick brown fox jumped over the 300 series tractor';

我想提取 LE300、LE 300 或仅提取 300(假设访客没有输入 LE)

因此,我创建了一个 preg_match() 来拉出这些位。

使用以下代码,我可以提取LE300或LE 300,而不仅仅是300。

preg_match('/(?<='s|^)[a-zA-Z]{1,3} ?'d'd'd? ?[a-zA-Z]{0,1}? (?='s|$)/', $string, $matches);

我试过了;

preg_match('/(?<='s|^)[a-zA-Z]{1,3} ?'d'd'd? ?[a-zA-Z]{0,1}? ?| [0-9]{2,3} (?='s|$)/', $Title, $matches);

preg_match('/(?<='s|^)[a-zA-Z]{1,3} ?'d'd'd? ?[a-zA-Z]{0,1}? ?| 'd'd'd? (?='s|$)/', $Title, $matches); 

但无论我做什么,我都无法提取一个独立的 2 或 3 位数字。

如果有人对如何纠正此问题有任何想法,如果您能与我分享,我将

不胜感激

您的正则表达式可能比这简单得多。 从本质上讲,您正在寻找可能的 2 个大写字母,后跟一个可选的空格,然后是 3 位数字。 这可以实现:

preg_match('/((?:[A-Z]{2})?'s*'d{3})/', $string1, $matches);

如果你想允许小写的le,那么你可以这样做:

preg_match('/((?:[A-Za-z]{2})?'s*'d{3})/', $string1, $matches);

如果字符串的其余部分是常量,那么它可以非常简单。

preg_match('/The quick brown fox jumped over the (.*) tractor/', $string1, $matches);