【问题标题】:Match group of words in lower or upper case n regex [duplicate]匹配小写或大写n正则表达式中的单词组[重复]
【发布时间】:2014-06-25 21:07:34
【问题描述】:

我需要一个正则表达式来匹配一组小写或大写的单词 例如我有一个单词数组:

订单、物品、朋友、学生

我想要一个像 OrdeRsordersstuDentsFrIendsstudents 这样的词来匹配正则表达式。

我真的很感谢您的帮助。谢谢

【问题讨论】:

  • /i flag
  • @mario 当我尝试 [orders,items]/i 时,它不起作用
  • 这不是正则表达式中alternatives 的有效语法。
  • 如果列表遵循格式,您甚至不需要正则表达式。
  • @mario 你是说这个吗? \b(猫|狗)\b#i ?

标签: php regex preg-match


【解决方案1】:

为此,您需要使用不区分大小写的正则表达式 i 标志。

<?php
$string = "orders,items,friends,students OrdeRs or orders OR stuDents or FrIends or students";

preg_match_all('/(orders|items|friends|students)/i', $string, $result, PREG_PATTERN_ORDER);
for ($i = 0; $i < count($result[1]); $i++) {
    echo $result[1][$i]."\n";
}
/*
orders
items
friends
students
OrdeRs
orders
stuDents
FrIends
students
*/
?>

DEMO

正则表达式解释:

(orders|items|friends|students)

Options: Case insensitive; 

Match the regex below and capture its match into backreference number 1 «(orders|items|friends|students)»
   Match this alternative (attempting the next alternative only if this one fails) «orders»
      Match the character string “orders” literally (case insensitive) «orders»
   Or match this alternative (attempting the next alternative only if this one fails) «items»
      Match the character string “items” literally (case insensitive) «items»
   Or match this alternative (attempting the next alternative only if this one fails) «friends»
      Match the character string “friends” literally (case insensitive) «friends»
   Or match this alternative (the entire group fails if this one fails to match) «students»
      Match the character string “students” literally (case insensitive) «students»

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-23
    • 1970-01-01
    • 2018-04-07
    • 2020-05-14
    相关资源
    最近更新 更多