問題描述
我想將字符串轉換為浮點數.例如
I would like to convert a string into floating numbers. For example
152.15 x 12.34 x 11mm
進入
152.15, 12.34 and 11
并存儲在一個數組中,使得 $dim[0]=152.15, $dim[1]=12.34, $dim[2]=11.
and store in an array such that $dim[0]=152.15, $dim[1]=12.34, $dim[2]=11.
我還需要處理諸如
152.15x12.34x11 mm
152.15mmx12.34mm x 11mm
謝謝.
推薦答案
$str = '152.15 x 12.34 x 11mm';
preg_match_all('!d+(?:.d+)?!', $str, $matches);
$floats = array_map('floatval', $matches[0]);
print_r($floats);
(?:...)
正則表達式構造就是所謂的 非捕獲組.這意味著該塊沒有在 $mathces
數組的一部分中單獨返回.這不是絕對必要的在這種情況下,但這是一個有用的結構.
The (?:...)
regular expression construction is what's called a non-capturing group. What that means is that chunk isn't separately returned in part of the $mathces
array. This isn't strictly necessary in this case but is a useful construction to know.
注意:調用floatval()
在元素上也不是絕對必要的,因為如果您嘗試在算術運算或類似操作中使用它們,PHP 通常會正確處理類型.不過,這并沒有什么壞處,尤其是只作為一個班輪.
Note: calling floatval()
on the elements isn't strictly necessary either as PHP will generally juggle the types correctly if you try and use them in an arithmetic operation or similar. It doesn't hurt though, particularly for only being a one liner.
這篇關于從 PHP 中的字符串中提取浮點數的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!