preg_match exclude a number
I have this code
preg_match("/\bHTTP(.)+ (\d{3})/", $string)
In the last pattern I have to check for a 3 digit number that can be compo开发者_JAVA技巧sed by any digit but should not create a number like 404
or 401
, how can I do it?
You can use the negative lookahead assertion to ensure that the matched string does not have a 404
or a 401
as:
preg_match("/\bHTTP(.+) (?!404|401)(\d{3})/", $string)
Rubular Link
The more values you want to exclude, the more complicated this will get, but
preg_match("/\bHTTP(.+) ([0-35-9]\d{2}|4[1-9]\d|40[0235-9])/", $string)
will match any three digit number that doesn't start with 4,
or any three digit number that starts with 4 but doesn't start with 40,
or any three digit number that starts with 40 but isn't 401 or 404.
explanation:
A negative lookahead ?!
looks for text that does not match the specified pattern.
A positive lookahead looks for a pattern to match but not to return.
http://www.regular-expressions.info/lookaround.html
?!
do not match the following pattern404|401
either404
or401
, so the|
is used for alternatives
精彩评论