2011-03-18 135 views
0

我试图从表单中修改一个变量。 我想摆脱任何“,”但保留“。”同时,将其更改为 “%2E”修改价格变量

$price = '6,000.65'; 

//$price = preg_replace('.', '%2e', $price); 
$price = urlencode($price); 

echo $price; 
+1

请说明原因 – 2011-03-18 09:12:58

回答

1

这是你的问题的确切结果:

$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); 

参考文献:

+0

您也可以执行'$ price =(float)$ price'来摆脱它,并将其转换为实际的数字而不是字符串,并且删除任何非一次输入的数字输入。 – Phoenix 2011-03-18 09:29:06

+0

@Phoenix:我已经考虑过这个问题,但它不适用于大数字。我会举一个例子。 – Lekensteyn 2011-03-18 09:34:30

0
$price = '6,000.65'; 
$price  = str_replace(',','',str_replace('.', '%2e',&$price)); 

$price = urlencode($price);