Reputation: 27749
I'm looking for a regex that will match against: X_X
Where X is always a number great than zero and there must be an underscore character in between the two numbers.
EDIT: When I run
$pattern = "[1-9]_[1-9]";
if (preg_match($pattern, $key))
return TRUE;
I get a Warning:
Message: preg_match() [function.preg-match]: Unknown modifier '_'
Upvotes: 2
Views: 133
Reputation: 12495
A regexp string is made of regexp and modifiers (like i, m). Since they are both part of a single string, there is a mandatory delimiter between them - a single character, like a pipe, a slash, semicolon. Since you can use any symbol, you have to declare which one you will be using. The choice is declared with the first char of your regexp string. if it is /, then the delimiter will be /. If it is |, then the delimiter will be |.
So these are perfectly equivalent (regexp 'test', modifier 'i'):
preg_match("/test/i");
preg_match("|test|i");
preg_match(":test:i");
if you use your delimiter earlier, PHP interprets the next char as a modifier. This is what happened to you (since you began with [, PHP interpreted ] as a delimiter and _ as a modifier).
The pattern you are looking for is:
$pattern = '/^\d+_\d+$/';
Note the ^ and $ ! Omitting these (as most of the other answers do) is a huge error (because it allows any string before and after the matched part; if you forgot the ^, -20_1 would also match, because it has a valid substring: 20_1).
Upvotes: 1
Reputation: 208475
The following should do what you want:
preg_match("/[1-9]\d*_[1-9]\d*/", $key)
Note that this will work for numbers with more than one digit as well, if X
in your example is only a single digit number then you can remove the \d*
.
Upvotes: 5
Reputation: 8831
You can define character classes matching all numbers between 1-9 using [1-9].
$pattern = "[1-9]_[1-9]";
Upvotes: 0