我想从存储在数据库中的字符串中提取一个数字(4个位置)。
例如:“山宾馆(2340米)在拉冬”如何做到这一点?这个数字有可能是2340M
发布于 2011-10-16 21:18:43
<?php
//$string = 'Mountain guesthouse (2340m) in Radons';
//preg_match('#([0-9]+)m#is', $string, $matches);
//$peak = number_format($matches[1], 0, ',', '.');
//EDIT
$string = 'Mountain guesthouse (23.40m) in Radons';
$preg_match('#([0-9\.]+)m#is', $string, $matches);
$peak=$matches[1];
echo $peak . 'm'; # 23.40m
?>直播:http://ideone.com/42RT4
发布于 2011-10-16 21:13:20
preg_match('/\d\.?\d{3}/', $text, $matches);匹配后跟可选点的数字和另外3个数字。
php > $text = "Mountain guesthouse (2340m) in Radons";
php > preg_match('/\d\.?\d{3}/', $text, $matches);
php > print_r($matches);
Array
(
[0] => 2340
)发布于 2011-10-16 21:11:45
你的问题有点含糊。M总是数字的一部分吗?你想把它也提取出来吗?数字总是由4位数字组成吗?下面匹配不带科学记数的任何整数或浮点整数。
if (preg_match('/[0-9]*\.?[0-9]+/', $subject, $regs)) {
$result = $regs[0];
#check if . is present and if yes length must be 5 else length must be 4
if (preg_match('/\./', $result) && strlen($result) == 5) {
#ok found match with . and 4 digits
}
elseif(strlen($result) == 4){
#ok found 4 digits without .
}
}https://stackoverflow.com/questions/7784480
复制相似问题