Вопрос

I'm using the following PCRE expression with preg_match to check if the value I want is a digit or not.

(?P<id>[\d]+)

It works, but now I want it to match the same conditions except if the whole content equals 0 (zero).

Example result

1    valid
10   valid
0    invalid

Expression context

#^(?P<controller>.*?|home)(?:/(?P<action>.*?|index)(?:/(?P<id>[\d]+))?)?$#uD
Это было полезно?

Решение

Can you try this?

#^(?P<controller>home)(?:/(?P<action>index)(?:/(?P<id>[1-9][\d]*))?)?$#uD

In your example, just using the digits, it's matching first, so obviously 0 gets captured. Assuming your match string is more complex than that, in which case the "1-9 once and 0-9 0 or more times" should do it for you.

See: http://regex101.com/r/yK6mR5

Другие советы

You can use this regex:

^(?!0+$)(?P<id>\d+)$

Online Demo: http://regex101.com/r/dB2eT3

UPDATE:

Working regex:

'#^(?P<controller>[^/]*|home)(?:/(?P<action>[^/]*|index)(?:/(?!0+$)(?P<id>\d+))?)?$#'
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top