坚持PHP正则表达式

时间:2012-07-20 07:01:17

标签: php regex


我有大字符串,我需要检查是否存在超过3的数字。
意味着“some string2”将无效,但“some string 3”,“some string7”将是正确的。

5 个答案:

答案 0 :(得分:3)

preg_match('/some\s*string\s*([3-9][0-9]*|[1-9][0-9]+)/i', $haystack);

在这里工作example

但是,在检查了你的用例之后,它似乎正在检查应用程序描述中的特定版本,我也建议你只是从字符串中获取数字并将其与实际数字进行比较以确定它大于或等于3:

preg_match('/([0-9]+)/', $string, $matches);
if ($matches[1] >= 3) {
  // Do something
}

答案 1 :(得分:3)

正则表达式用于文本匹配,而不是算术。正确工作的正确工具......

preg_match('/([0-9]+)/', $string, $matches);
if ($matches[1] >= 3) {
  // Do something
}

答案 2 :(得分:1)

这不起作用?

$numberBiggerThanThree = preg_match('/([0-9]{2,}|[3-9])/', 'some long string 3');

答案 3 :(得分:1)

您匹配单词后跟可选空格,然后匹配大于2的数字。由于小数位,您可以控制:

(\w*\s*(?:[1-9]\d+|[3-9]))

一些小例子(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);

输出:

array(1) {
  [0]=>
  array(3) {
    [0]=>
    string(6) "than 3"
    [1]=>
    string(8) "string 3"
    [2]=>
    string(7) "string7"
  }
}

我希望这有用。

答案 4 :(得分:1)

我修改了Florian的解决方案:

[a-z]+\s?[a-z]+\s?([1-9][0-9]+|[3-9])

http://regexr.com?31ja1

它适用于任何字符串,而不仅仅是“某些字符串”,它只允许0或1个空白字符。