我試圖從表單中修改一個變量。 我想擺脫任何「,」但保留「。」同時,將其更改爲 「%2E」修改價格變量
$price = '6,000.65';
//$price = preg_replace('.', '%2e', $price);
$price = urlencode($price);
echo $price;
我試圖從表單中修改一個變量。 我想擺脫任何「,」但保留「。」同時,將其更改爲 「%2E」修改價格變量
$price = '6,000.65';
//$price = preg_replace('.', '%2e', $price);
$price = urlencode($price);
echo $price;
這是你的問題的確切結果:
$price = str_replace(',', '', $price);
$price = str_replace('.', '%2e', $price);
echo $price;
但是你爲什麼要urlencode呢.. 。?如果您想要去除不允許的字符(一切,但數字和一個點),可以使用下面的函數:
$price = preg_replace('/[^0-9.]/', '', $price);
// OP requested it...
$price = str_replace('.', '%2e', $price);
echo $price;
或者,也可以將字符串轉換成浮點數和使用number_format()
很好地格式化。
// note that numbers will be recognised as much as possible, but strings like `1e2`
// will be converted to 100. `1x2` turns into `1` and `x` in `0` You might want
// to apply preg_replace as in the second example
$price = (float)$price;
// convert $price into a string and format it like nnnn.nn
$price = number_format("$price", 2, '.', '');
echo $price;
第三個選項,以類似的方式工作。 %
是sprintf
的特殊字符,標誌着對話規範。 .2
告訴它有兩位小數,f
告訴它它是一個浮點數。
$price = sprintf('%.2f', $price);
echo $price;
// printf combines `echo` and `sprintf`, the below code does the same
// except $price is not modified
printf('%.2f', $price);
參考文獻:
您也可以執行'$ price =(float)$ price'來擺脫它,並將其轉換爲實際的數字而不是字符串,並且刪除任何非一次輸入的數字輸入。 – Phoenix 2011-03-18 09:29:06
@Phoenix:我已經考慮過這個問題,但它不適用於大數字。我會舉一個例子。 – Lekensteyn 2011-03-18 09:34:30
http://php.net/manual/en/function.str-replace.php
$newPhrase = str_replace($findWhat, $replaceWith, $searchWhere);
所以你的情況:
$newPrice = str_replace(",", "", $price);
$price = '6,000.65';
$price = str_replace(',','',str_replace('.', '%2e',&$price));
$price = urlencode($price);
請說明原因 – 2011-03-18 09:12:58