0

I need a regex to match a group of words in lower or upper case for example I have a array of words:

orders,items,friends,students

and I want a word like OrdeRs or orders OR stuDents or FrIends or students to match the regex.

I would really appriciate your help. thanks

Dester Dezzods
  • 919
  • 4
  • 14
  • 32
  • 1
    There's the [`/i` flag](http://www.php.net/manual/en/reference.pcre.pattern.modifiers.php) for that. – mario May 08 '14 at 13:02
  • @mario when I try [orders,items]/i , it doesn't work – Dester Dezzods May 08 '14 at 13:03
  • That's not the valid syntax for [alternatives](http://www.regular-expressions.info/alternation.html) in a regex. – mario May 08 '14 at 13:05
  • If the list follows a format you shouldn't even need regex. – Flosculus May 08 '14 at 13:09
  • @mario you mean this? \b(cat|dog)\b#i ? – Dester Dezzods May 08 '14 at 13:10
  • Yes, you're on the right track now. Remember to add an initial delimiter `#` though. * See also [Open source RegexBuddy alternatives](http://stackoverflow.com/questions/89718/is-there) and [Online regex testing](http://stackoverflow.com/questions/32282/regex-testing) for some helpful tools, or [RegExp.info](http://regular-expressions.info/) for a nicer tutorial. – mario May 08 '14 at 13:14

1 Answers1

0

For that you need to use a case insensitive regex i flag.

<?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

Regex Explanation:

(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»
Pedro Lobito
  • 75,541
  • 25
  • 200
  • 222