Page 583 - Beginning PHP 5.3
P. 583
Chapter 18: String Matching with Regular Expressions
So to match a digit character anywhere in the target string you could use either of the following two
expressions:
/[0-9]/
/\d/
Incidentally, you can also use a shorthand character class within a longhand class. The following
expression matches the letter “ e” or “ p ” , or any digit, in the target string:
/[ep\d]/
Here are some examples:
echo preg_match( “/\d[A-Z]/”, “3D” ); // Displays “1”
echo preg_match( “/\d[A-Z]/”, “CD” ); // Displays “0”
echo preg_match( “/\S\S\S/”, “6 & c” ); // Displays “1”
echo preg_match( “/\S\S\S/”, “6 c” ); // Displays “0”
To match any character at all, use a dot ( . ):
echo preg_match( “/He.../”, “Hello” ); // Displays “1”
Matching Multiple Characters
If you want to match the same character (or character class) multiple times in a row, you can use
quantifiers . A quantifier is placed after the character or character class, and indicates how many times that
character or class should repeat in the target string. The quantifiers are:
Quantifier Meaning
* Can occur zero or more times
+ Can occur one or more times
? Can occur exactly once, or not at all
{ n Must occur exactly n times
}
{ n, Must occur at least n times
}
{ n,m Must occur at least n times but no more than m times
}
For example, you can match a string of at least one digit with:
/\d+/
545
9/21/09 6:17:52 PM
c18.indd 545
c18.indd 545 9/21/09 6:17:52 PM