【问题标题】:Trouble Using the OR | operator in PHP preg_match使用 OR 时遇到问题 | PHP preg_match 中的运算符
【发布时间】:2013-11-08 23:41:26
【问题描述】:

使用以下通过 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 位数字。

如果有人对如何纠正这个问题有任何想法,如果你能与我分享,我将不胜感激

【问题讨论】:

  • 为什么不把{1,3}改成{0,3},这样数字前可以有零个字母?

标签: php regex preg-match


【解决方案1】:

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

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

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

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2018-04-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-14
      • 2022-08-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多