문제

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