This is an old revision of the document!
Regex Notation
Regex Quick Reference
Symbol | Description |
---|---|
[abc] | A single character: a, b or c |
[^abc] | Any single character but a, b, or c |
[a-z] | Any single character in the range a-z |
[a-zA-Z] | Any single character in the range a-z or A-Z |
^ | Start of line |
. | Any single character |
\s | Any whitespace character |
\S | Any non-whitespace character |
\d | Any digit |
\D | Any non-digit |
\w | Any word character (letter, number, underscore) |
\W | Any non-word character |
(…) | Capture everything enclosed |
(a|b) | a or b |
a? | Zero or one of a |
a* | Zero or more of a |
a+ | One or more of a |
a{3} | Exactly 3 of a |
a{3,} | 3 or more of a |
a{3,6} | Between 3 and 6 of a |
General Tokens:
\n | Newline |
\r | Carriage return |
\t | Tab |
\f | Form-feed |
\0 | Null character |
Anchors:
\G | Start of match |
^ | Start of string |
\A | Start of string |
$ | End of string |
\Z | End of string |
\z | Absolute end of string |
\b | Any word boundary character |
\B | Any non-word boundary |
\w | Any word character (letter, number, underscore) |
\W | Any non-word character |
Flags/Modifiers (eg: “/…/i”):
g | Blobal |
i | Case insensitive |
m | Multiline (make dot match newlines) |
s | Single line |
u | Unicode |
x | Ignore whitespace |
o | Perform #{…} substitutions only once |
X | eXtended |
A | Anchor |
J | Duplicate group names |
Using Regex in PHP
Can be used as ereg()
or preg_match()
. Here is a comparison:
<?php if(ereg('[^0-9A-Za-z]',$test_string)) // will be true if characters arnt 0-9, A-Z or a-z. if(preg_match('/[^0-9A-Za-z]/',$test_string)) // this is the preg_match version. the /'s are now required. ?>
Using options:
<?php // The "i" after the pattern delimiter indicates a case-insensitive search if (preg_match("/php/i", "PHP is the web scripting language of choice.")) { echo "A match was found."; } else { echo "A match was not found."; } ?>
Example using preg_replace()
:
// Strip ending commas $str = preg_replace('/,$/s', '', $str); // Strip leading/trailing commas with whitespace around $str = preg_replace('/^[,\s]+|[\s,]+$/', '', $str);