3

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        
)
Jakub Hampl
  • 39,863
  • 10
  • 77
  • 106
Mokus
  • 10,174
  • 18
  • 80
  • 122

4 Answers4

3

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.

yan
  • 20,644
  • 3
  • 38
  • 48
3

You have to mach more than one digit:

preg_match_all("/[0-9]+/", $string, $ret);
Florian
  • 3,145
  • 1
  • 27
  • 38
3

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

Jakub Hampl
  • 39,863
  • 10
  • 77
  • 106
3

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"
  }
}
Wes
  • 6,455
  • 3
  • 22
  • 26