我有一些字符串:
some words 1-25 to some words 26-50
more words 1-10
words text and words 30-100
如何从字符串中找到并获取所有“1-25”和“26-50”以及更多
答案 0 :(得分:5)
如果是整数,请匹配多个数字:\d+
。要匹配整个范围表达式:(\d+)-(\d+)
。
也许您还想在短划线和数字之间留出空格:
(\d+)\s*-\s*(\d+)
也许你想确保表达式是自由的,即不是单词的一部分:
\b(\d+)\s*-\s*(\d+)\b
\b
是零宽度匹配并测试字边界。这个表达禁止事物
比如“Some1 -2text
”但允许“Some 1-2 text
”。
答案 1 :(得分:3)
您可以使用正则表达式执行此操作:
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]中在相同的索引处。
答案 2 :(得分:0)
我认为这一行已足够
preg_replace("/[^0-9]/","",$string);