簡體   English   中英

從字符串中提取數字(4個位置)

[英]extract number (4 positions) from a string

我想從存儲在數據庫中的字符串中提取一個數字(4個位置)。

例如,“拉頓斯山上的旅館(2340m)”該怎么辦? 可能像是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
實時編輯: 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總是數字的一部分嗎? 您是否也要提取它? 數字是否總是由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 .
    }
}

(根據@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

?>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM