php:如何在字符串中查找数字?

php:如何在字符串中查找数字?,php,regex,preg-match,Php,Regex,Preg Match,我有一些字符串,比如: some words 1-25 to some words 26-50 more words 1-10 words text and words 30-100 如何从字符串中查找和获取所有的“1-25”和“26-50”以及更多的值如果是整数,请匹配多个数字:\d+。要匹配整个范围表达式:(\d+)-(\d+) 也许您还希望在破折号和数字之间允许空白: (\d+)\s*-\s*(\d+) 也许你想确保这个表达是自由的,也就是说,不是一个词的一部分: \b(\d+)\s*

我有一些字符串,比如:

some words 1-25 to some words 26-50
more words 1-10
words text and words 30-100

如何从字符串中查找和获取所有的“1-25”和“26-50”以及更多的值

如果是整数,请匹配多个数字:
\d+
。要匹配整个范围表达式:
(\d+)-(\d+)

也许您还希望在破折号和数字之间允许空白:

(\d+)\s*-\s*(\d+)
也许你想确保这个表达是自由的,也就是说,不是一个词的一部分:

\b(\d+)\s*-\s*(\d+)\b
\b
是零宽度匹配,用于测试单词边界。这个表达禁止任何事情
与“
Some1-2text
”类似,但允许“
Some1-2text

您可以使用正则表达式执行此操作:

echo preg_match_all('/([0-9]+)-([0-9]+)/', 'some words 1-25 to some words 26-50 more words 1-10 words text and words 30-100', $matches);
4
print_r($matches);
Array
(
    [0] => Array
        (
            [0] => 1-25
            [1] => 26-50
            [2] => 1-10
            [3] => 30-100
        )

    [1] => Array
        (
            [0] => 1
            [1] => 26
            [2] => 1
            [3] => 30
        )

    [2] => Array
        (
            [0] => 25
            [1] => 50
            [2] => 10
            [3] => 100
        )

)

对于每个范围,第一个值在同一索引的数组[1]中,第二个值在数组[2]中。

我认为这行就足够了

preg_replace("/[^0-9]/","",$string);

我们可以谈谈我想听听你的建议吗?我试试:preg_match_all((\d+)\s*-\s*(\d+),“一些单词1-25到一些单词26-50”,$matches);事实并非如此work@motioz:您需要,例如
/(\d+)\s*-\s*(\d+)/
。这是如此普遍,以至于答案中没有提到保持模式更具可读性。