Regular Expression | Will match... |
---|---|
/foo/ | The string "foo" |
/^foo/ | 'foo' at the start of a string |
/foo$/ | 'foo' at the end of a string |
/^foo$/ | 'foo' when it is alone on a string |
/[abc]/ | a, b, or c |
/[a-z]/ | Any lowercase letter |
/[^A-Z]/ | Any character that is not a uppercase letter |
/(gif|jpeg)/ | Matches either 'gif' or 'jpeg' |
/[a-z]+/ | One or more lowercase letters |
/[0-9\.\-]/ | Аny number, dot, or minus sign |
/^[a-zA-Z0-9_]{1,}$/ | Any word of at least one letter, number or _ |
/([wx])([yz])/ | wy, wz, xy, or xz |
/[^A-Za-z0-9]/ | Any symbol (not a number or a letter) |
/([A-Z]{3}|[0-9]{4})/ | Three letters or four numbers |
/ab*/ | An 'a' followed by ZERO or more 'b's |
/ab+/ | An 'a' followed by ONE or more 'b's |
/ab?/ | An 'a' followed by zero OR one 'b' |
/ab{2}/ | An 'a' followed by exactly two b's |
/ab{2,}/ | An 'a' followed by two or more b's |
/a(bc)/ | An 'a' followed by zero or one copy of 'bc' |
/a(bc)*/ | An 'a' followed by zero or more copies of 'bc' |
/a(bc){1,5}/ | An 'a' followed by one through five copies of 'bc' |
/a(bc){*}/ | An 'a' followed by zero or more copies of 'bc' |
/a.[0-9]/ | An 'a' followed by a digit |
/[a-d]/ | An 'a' followed by lowercase letters 'a' through 'd' |
/(a|b)*c/ | Has a sequence of a's or b's ending in a c |
/(b|cd)ef/ | Has either 'aef' or 'cdef' in it |
/^.{3}$/ | Has exactly 3 characters. |
/$|¥[0-9]/ | Has a $ or ¥ followed by 0-9 |
/^[a-zA-Z]/ | Starts with any letter. |
/[0-9]%/ | Single digit before a percent sign. |
/,[a-zA-Z0-9]$/ | Ends in a comma followed by an alphanumeric character. |
/%[^a-zA-Z]%/ | Single character that is NOT a letter between two percent signs. |
/[\s,]+/ | Same as explode on ' ' via preg_split() |
/.at/ | Three-character string ending with 'at', including 'hat', 'cat', and 'bat'. |
/[^b]at/ | Same as above except 'bat'. |
/[^bc]at/ | Same as above except 'bat' and 'cat'. |
/^[bc]at/ | Allows 'bat' and 'cat', but only at the start of the string. |
/[bc]at/$ | Allows 'bat' and 'cat', but only at the end of the string. |
/\[.\]/ | Any single character surrounded by '[' and ']', such as [a], [b]. |
/a.+c/ | Greedy : abcdefghijklmc will return 'abcdefghijklmc'. |
/a.*c/ | Greedy : abcdefghijklmc will return 'abcdefghijklmc'. |
/a.+?c/ | Lazy : abcdefghijklmc will return 'abc'. |
/a.*?c/ | Lazy : abcdefghijklmc will return 'abc'. |
/a.+c/ULazy : abcdefghijklmc will return 'abc'. |
|
/a.*c/U | Lazy : abcdefghijklmc will return 'abc'. |
The standard quantifiers in Regular Expressions are GREEDY, meaning they match as much as they can, only giving back as necessary to match the remainder of the regex. By using a LAZY quantifier, the expression tries the minimal match first.
The LAZY qualifier can be expressed as a "?" inside the pattern OR "U" at the end of the pattern, such as /a.*?c/ and /a.*c/U that produce the same result.