問題描述
我想將字符串轉(zhuǎn)換為浮點(diǎn)數(shù).例如
I would like to convert a string into floating numbers. For example
152.15 x 12.34 x 11mm
進(jìn)入
152.15, 12.34 and 11
并存儲(chǔ)在一個(gè)數(shù)組中,使得 $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);
(?:...)
正則表達(dá)式構(gòu)造就是所謂的 非捕獲組.這意味著該塊沒有在 $mathces
數(shù)組的一部分中單獨(dú)返回.這不是絕對(duì)必要的在這種情況下,但這是一個(gè)有用的結(jié)構(gòu).
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.
注意:調(diào)用floatval()
在元素上也不是絕對(duì)必要的,因?yàn)槿绻鷩L試在算術(shù)運(yùn)算或類似操作中使用它們,PHP 通常會(huì)正確處理類型.不過,這并沒有什么壞處,尤其是只作為一個(gè)班輪.
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.
這篇關(guān)于從 PHP 中的字符串中提取浮點(diǎn)數(shù)的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!