簡體   English   中英

從字符串中提取格式化的數字

[英]Extract a formatted number from a string

我想從字符串中提取一個數字,字符串就像1,239 peoples 我需要從上面的字符串輸出1239 我使用以下便宜的方法來提取該數字....

$text='1,239 peoples';
$text=str_replace(',','',$text);
preg_match_all('!\d+!', $text, $matches);
echo $matches[0][0];

有沒有更好的解決方案..提前謝謝......

你可以用任何東西替換字符串中不是數字的所有內容,這樣就會給你一個只有數字的字符串。

$string = preg_replace("/[^\d]/", "", $string);
echo $string;

一種更安全的方法是首先提取你想要的, 只有在給它好格式之后,例如:

if (preg_match('~\d+(?:,\d+)*(?:\.\d+)?~', $string, $match))
    $result = str_replace(',', '', $match[0]);
//This will replace anything that is not a number with a blank string.
$number = preg_replace("#[^0-9]*#", "", "1,123");

盡管如此,“1,233.90”仍然很棒。

暫無
暫無

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

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