Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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        
)
like image 396
OHLÁLÁ Avatar asked Feb 05 '26 02:02

OHLÁLÁ


2 Answers

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"
  }
}
like image 180
Wes Avatar answered Feb 06 '26 15:02

Wes


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.

like image 37
yan Avatar answered Feb 06 '26 16:02

yan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!