I am trying to validate a string of 3 numbers followed by / then 5 more numbers I thought this would work
(/^([0-9]+[0-9]+[0-9]+/[0-9]+[0-9]+[0-9]+[0-9]+[0-9])/i)
but it doesn't, any ideas what i'm doing wrong
Try this
preg_match('@^\d{3}/\d{5}@', $string)
The reason yours is not working is due to the +
symbols which match "one or more" of the nominated character or character class.
Also, when using forward-slash delimiters (the characters at the start and end of your expression), you need to escape any forward-slashes in the pattern by prefixing them with a backslash, eg
/foo\/bar/
PHP allows you to use alternate delimiters (as in my answer) which is handy if your expression contains many forward-slashes.
First of all, you're using /
as the regexp delimiter, so you can't use it in the pattern without escaping it with a backslash. Otherwise, PHP will think that you're pattern ends at the /
in the middle (you can see that even StackOverflow's syntax highlighting thinks so).
Second, the +
is "greedy", and will match as many characters as it can, so the first [0-9]+
would match the first 3 numbers in one go, leaving nothing for the next two to match.
Third, there's no need to use i
, since you're dealing with numbers which aren't upper- or lowercase, so case-sensitivity is a moot point.
Try this instead
/^\d{3}\/\d{5}$/
The \d
is shorthand for writing [0-9]
, and the {3}
and {5}
means repeat 3 or 5 times, respectively.
(This pattern is anchored to the start and the end of the string. Your pattern was only anchored to the beginning, and if that was on purpose, the remove the $
from my pattern)
I recently found this site useful for debugging regexes: http://www.regextester.com/index2.html
It assumes use of /.../
(meaning you should not include those slashes in the regex you paste in).
So, after I put your regex ^([0-9]+[0-9]+[0-9]+/[0-9]+[0-9]+[0-9]+[0-9]+[0-9])
in the Regex box and 123/45678
in the Test box I see no match. When I put a backslash in front of the forward slash in the middle, then it recognizes the match. You can then try matching 1234/567890
and discover it still matches. Then you go through and remove all the plus signs and then it correctly stops matching.
What I particularly like about this particular site is the way it shows the partial matches in red, allowing you to see where your regex is working up to.
+
characters are doing?