开发者

preg_match custom pattern

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?


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.
}


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);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜