问题
I have been learning PHP for some time now and I wanted one clarification.
I have seen the preg_match
function called with different delimiting symbols like:
preg_match('/.../')
and
preg_match('#...#')
Today I also saw %
being used.
My question is two part:
What all characters can be used?
And is there a standard ?
回答1:
Any
- non-alphanumeric
- non-whitespace and
- non-backslash ASCII character
can be used as delimiter.
Also if you using the opening punctuation symbols as opening delimiter:
( { [ <
then their corresponding closing punctuation symbols must be used as closing delimiter:
) } ] >
The most common delimiter is /
.
But sometimes it's advised to use a different delimiter if a /
is part of the regex.
Example:
// check if a string is number/number format:
if(preg_match(/^\d+\/\d+$/)) {
// match
}
Since the regex contains the delimiter, you must escape the delimiter found in the regex.
To avoid the escaping it is better to choose a different delimiter, one which is not present in the regex, that way your regex will be shorter and cleaner:
if(preg_match(#^\d+/\d+$#))
来源:https://stackoverflow.com/questions/4352377/beginner-php-help-needed