This preg_match
will never work even though I think its the right thing.
I'm trying to check a string so that it's structured as follows
$value = US 01 02 1406034963 .JPG //I've put spaces in. The real one is below.
So:
The first part (US) is alphabets, only two characters from a-z
The second part (01) is a value 00 or 01
The third part (02) is digits 0-9 from 2 - 10 (can be 2 to 10 digits long)
The fourth part (1406034963) is a 10 digit figure, and only 10 digits
The fifth part is .jpg or .jpeg or .png. or .gif
But, my function always returns false. Can you please help?
//
function preset($value) {
if(preg_match('/^[a-z]{2}[00|01][0-9]{2,10}[0-9]{10}[.jpg|.jpeg|.png.|.gif]$/',$value)) {
return true;
} else {
return false;
}
}
$value = 'US01021406034963.JPG';
if(preset($value)) {
echo 'Yeah!';
} else {
echo 'Boo!';
}
[]
denotes a character class. Simply put, a character class is a way of denoting a set of characters in such a way that one character of the set is matched.
You're trying to use alternation inside character classes. It will not work as you expect it to. For example, the regex [00|01]
would match 0
, the literal character |
, or 1
, and not 00
or 01
.
To match either of the set, you can simply use grouping. In this case, you're not going to use the matched text anywhere, so you can use non-capturing groups. (?:00|01)
is a non-capturing group that will match either 00
or 01
. You can also shorten it and write just 0[01]
, but that totally depends on your taste.
And currently, your expression only matches lower-case strings. If you want it to work with upper-case, or even mixed-case strings, you can simply use the i
modifier. It will make the pattern match the string case-insensitively.
You can simplify your function to just:
function preset($value) {
return (bool) preg_match('/^[a-z]{2}(?:00|01)[0-9]{2,10}[0-9]{10}\.(?:jpe?g|png|gif)$/i',$value);
}
You cannot place whole words inside of a character class, use a non-capturing group instead.
/^[a-z]{2}0[01][0-9]{2,10}[0-9]{10}\.(?:jpe?g|png|gif)$/i
You are erroneously using square (character class) instead of round (alternation) brackets in some places:
[00|01]
should be (00|01)
.
[.jpg|.jpeg|.png.|.gif]
should be \.(jpe?g|png|gif)
.