我想用字串之外的公式計算字串,有時我會得到兩個用空格分隔的數字的字串,我的公式只是計算字串中的第一個數字。
$string = "225cm x 70cm";
$outputString = preg_replace('/[^0-9]/ ', ' ', $string);// output here is string(12) "225 70 "
$inches = intval($outputString) * 0.39370;
$inches_pre = round($inches / 0.5) * 0.5; // output here is just 85 instead of string "85.5 27.5"
uj5u.com熱心網友回復:
您可以使用
$string = "225cm x 70cm";
if (preg_match_all('/\d (?:\.\d )?/', $string, $m)) {
$inches = implode(" ", array_map(function ($x) { return round(intval($x) * 0.39370 / 0.5) * 0.5; }, $m[0]));
echo $inches;
}
// => 85.5 27.5
請參閱PHP 演示。
使用preg_match_all('/\d (?:\.\d )?/', $string, $m),您將所有數字提取到 中$m[0],然后在 an 中處理每個數字,array_map然后使用 將結果連接到單個字串中implode。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/383640.html
上一篇:以優雅的方式轉換字串scala
下一篇:QRegEx匹配純色調顏色
