tags:

views:

28

answers:

2

I'm trying to figure out how to make custom pattern to use with preg_match / preg_match_all.

I need to find [A-Z]{3}[a-z]{1}[A-Z]{3}, that would be for an example AREfGER. 3 uppercase, 1 lowercase and 3 uppercase.

anyone know how to make a pattern for this?

+2  A: 

You can do:

if(preg_match('/^[A-Z]{3}[a-z][A-Z]{3}$/',$input)) {
  // $input has 3 uppercase, 1 lowercase and 3 uppercase.
}

You can drop the {1} as its redundant.

Also make sure you add start anchor ^ and end anchor $. Without them even if the pattern is found anywhere in the input, a success will be reported. Example @AREfGER#

EDIT:

To find all matches in a text you can use preg_match_all as:

if(preg_match_all('/([A-Z]{3}[a-z][A-Z]{3})/',$input,$match)) {
  // array $match[1] will have all the matches.
}
codaddict
is it possible to list all matches?
Endre Hovde
If you just want to see the matches do this after you made the `preg_match_all()`-call that codaddict suggests: `echo '<pre>';print_r($matches[1]);echo'</pre>';exit;`
faileN
+2  A: 

As simple as:

preg_match('#[A-Z]{3}[a-z][A-Z]{3}#', $some_string);

Or if this has to match the string as a whole: Use Start- and End-Anchor

preg_match('#^[A-Z]{3}[a-z][A-Z]{3}$#', $some_string);
faileN