I've seen the regular expression '!\d!'
inside the PHP preg_match
function. What the heck is this?
2 Answers
From the PHP PCRE docs:
When using the PCRE functions, it is required that the pattern is enclosed by delimiters. A delimiter can be any non-alphanumeric, non-backslash, non-whitespace character.
In this case, it's simply using !
as the delimiter. Often it's used if you want to use the normal delimiter within the regex itself without having to escape it. Not really necessary in this case since the rest of the regex is simply \d
, but it comes in handy for things like checking that a path contains more than three directory levels. You can use either of:
/\/.*\/.*\/.*\/ blah blah blah /
or:
!/.*/.*/.*/ blah blah blah !
Now they haven't been tested thoroughly, and may not work entirely as advertised, but you should get the general idea re the minimal escaping required.
Another example (from the page linked to above) is checking if a string starts with the http://
marker. Either of these two:
/^http:\/\//
!^http://!
would suffice, but the second is easier to understand.
!
is used as delimiter, \d
matches the single digit.
It is the same as /[0-9]/
-
1Thanks, I thought that you always have to use the character "/". I didn't know that I can substitute it.– mosceoSep 25, 2012 at 9:13
preg_match
doc page to the PCRE regex delimiters doc page. And you have to know you are looking for "regex delimiter", but then you already know the answer...