从字符串中提取数字(4个位置)


extract number (4 positions) from a string

我想从存储在数据库中的字符串中提取一个数字(4个位置)。

。"拉东山区宾馆(2340米)"如何做到这一点呢?这个数字可能是2.340m

<?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
Edit live: https://ideone.com/hNJxG

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
)

你的问题有点模糊。m总是数字的一部分吗?你也想把它取出来吗?这个数字总是由四位数字组成吗?下面的语句匹配任何不带科学记数法的整数或浮点整数。

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

(编辑自@webarto的回答)

<?php
$string = 'Mountain guesthouse (23.40m) in Radons';
preg_match('#([0-9'.]+)m#is', $string, $matches);
$peak = $matches[1];
echo $peak . 'm'; # 2.340m
?>