2

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

3 Answers 3

5

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”.

Sign up to request clarification or add additional context in comments.

3 Comments

can we talk i want your advice
i try: preg_match_all("(\d+)\s*-\s*(\d+)","some words 1-25 to some words 26-50", $matches); It does not work
@motioz: You need to enclose the regular expressions into delimiters, e.g. /(\d+)\s*-\s*(\d+)/. That's so common that it was not mentioned in the answer to keep the patterns more readable.
3

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.

Comments

0

I think this line is enough

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.