Mokus
Mokus

Reputation: 10400

Get number from a string

I have a string for example "lorem 110 ipusm" and I want to get the 110 I already tried this:

preg_match_all("/[0-9]/", $string, $ret);

but this is returning this:

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

I want something like this

Array
(
    [0] => 110        
)

Upvotes: 3

Views: 1787

Answers (4)

Wes
Wes

Reputation: 6585

To catch any floating point number use:

preg_match_all("/[+-]?\d+[\d\.Ee+]*/", $string, $matches);

for example:

<?
$string = 'ill -1.1E+10 ipsum +1,200.00 asdf 3.14159, asdf';
preg_match_all("/[+-]?\d+[\d\.Ee+]*/", $string, $matches);
var_dump($matches);
?>

when run gives:

array(1) {
  [0]=>
  array(4) {
    [0]=>
    string(8) "-1.1E+10"
    [1]=>
    string(2) "+1"
    [2]=>
    string(6) "200.00"
    [3]=>
    string(7) "3.14159"
  }
}

Upvotes: 3

Jakub Hampl
Jakub Hampl

Reputation: 40533

Use /\d+/ - that should solve it.

Upvotes: 3

Florian
Florian

Reputation: 3171

You have to mach more than one digit:

preg_match_all("/[0-9]+/", $string, $ret);

Upvotes: 3

yan
yan

Reputation: 20982

Use the + (1 or more match) operator:

preg_match_all("/[0-9]+/", $string, $ret);

Also, are you trying to support signs? decimal points? scientific notation? Regular expressions also support a shorthand for character classes; [0-9] is a digit, so you can simply use \d.

Upvotes: 3

Related Questions