Reputation: 564
I need to validate that the Android version in a big string is more than 3.
In other words, "Android 2" will be invalid, but "Android 3" and "Android 7" will be correct.
Upvotes: 0
Views: 93
Reputation: 8700
This wouldn't work?
$numberBiggerThanThree = preg_match('/([0-9]{2,}|[3-9])/', 'some long string 3');
Upvotes: 1
Reputation: 17831
preg_match('/some\s*string\s*([3-9][0-9]*|[1-9][0-9]+)/i', $haystack);
And here the working example
But, after examining your use-case, which seems to be checking for a specific version in an application description, I too would advise you to just get the number out of the string and compare it to an actual number to be sure it's larger or equal than 3:
preg_match('/([0-9]+)/', $string, $matches);
if ($matches[1] >= 3) {
// Do something
}
Upvotes: 3
Reputation:
I modified Florian's solution:
[a-z]+\s?[a-z]+\s?([1-9][0-9]+|[3-9])
It works for any string and not just "some string" and it allows only 0 or 1 whitespace character.
Upvotes: 1
Reputation: 197682
You match a word followed by an optional space and then the number greater than 2. Thanks to the decimal places you can control that:
(\w*\s*(?:[1-9]\d+|[3-9]))
Some little example (demo):
$subject = 'I have big string in that I need to check if number is present which is more than 3.
Means "some string2" will be invalid , but "some string 3","some string7" will be correct.';
$pattern = '(\w*\s*(?:[1-9]\d+|[3-9]))';
$r = preg_match_all($pattern, $subject, $matches);
var_dump($matches);
Output:
array(1) {
[0]=>
array(3) {
[0]=>
string(6) "than 3"
[1]=>
string(8) "string 3"
[2]=>
string(7) "string7"
}
}
I hope this is helpful.
Upvotes: 1
Reputation: 46836
Regex is for text matching, not arithmetic. Right tool for the right job...
preg_match('/([0-9]+)/', $string, $matches);
if ($matches[1] >= 3) {
// Do something
}
Upvotes: 3