Reputation: 662
I have some strings like:
some words 1-25 to some words 26-50
more words 1-10
words text and words 30-100
how can I find and get from string all of the "1-25" and the "26-50" and more
Upvotes: 2
Views: 8408
Reputation: 1464
I think this line is enough
preg_replace("/[^0-9]/","",$string);
Upvotes: 0
Reputation: 3358
You can do this with regular expressions:
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
)
)
For each range the first value is in array[1] and the second is in array[2] at the same index.
Upvotes: 3
Reputation: 546183
If it’s integers, match multiple digits: \d+
. To match the whole range expression: (\d+)-(\d+)
.
Maybe you also want to allow whitespace between the dash and the numbers:
(\d+)\s*-\s*(\d+)
And maybe you want to make sure that the expression stands free, i.e. isn’t part of a word:
\b(\d+)\s*-\s*(\d+)\b
\b
is a zero-width match and tests for word boundaries. This expression forbids things
like “Some1 -2text
” but allows “Some 1-2 text
”.
Upvotes: 5