我试图从表单中修改一个变量。 我想摆脱任何“,”但保留“。”同时,将其更改为 “%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