Christopher
Christopher

Reputation: 3469

preg_match - extract only numbers

I have a string like Results 1 - 20 of 400.

Considering this example, i need to get 1, 20 and 400 to 3 distinct variables.

I'm trying this code without success:

preg_match('/\d{1,}/', $text, $array);

Upvotes: 1

Views: 2504

Answers (1)

Rizier123
Rizier123

Reputation: 59701

This should work for you:

$text = "Results 1 - 20 of 400";
preg_match_all('/\d+/', $text, $array);
        //^^^^ Note here! 'preg_match_all' not 'preg_match' to get all matches! (Your regex would also work '/\d{1,}/')
print_r($array);

Output:

Array ( [0] => Array ( [0] => 1 [1] => 20 [2] => 400 ) )

For more information about preg_match_all() see the manual: http://php.net/manual/en/function.preg-match-all.php

And a quote from there:

preg_match_all — Perform a global regular expression match

Upvotes: 2

Related Questions