[英]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: 我有一个字符串,例如“lorem 110 ipusm”,我想获得110我已经尝试过这个:
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
)
Use the +
(1 or more match) operator: 使用+
(1个或多个匹配)运算符:
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
. [0-9]
是一个数字,所以你可以简单地使用\\d
。
你必须超过一位数:
preg_match_all("/[0-9]+/", $string, $ret);
使用/\\d+/
- 应解决它。
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"
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.