Get number from a string

北城以北 提交于 2020-01-03 19:34:31

问题


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        
)

回答1:


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"
  }
}



回答2:


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.




回答3:


You have to mach more than one digit:

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



回答4:


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



来源:https://stackoverflow.com/questions/5734187/get-number-from-a-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!