开发者

preg_match exclude a number

开发者 https://www.devze.com 2023-02-13 06:54 出处:网络
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 nu

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 pattern
  • 404|401 either 404 or 401, so the | is used for alternatives
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号