开发者

modify price variable

开发者 https://www.devze.com 2023-02-17 19:57 出处:网络
开发者_StackOverflow中文版I\'m trying to modify a variable from a form. I want to get rid of any \",\" but keep the \".\" while changing it to \"%2e\"
开发者_StackOverflow中文版

I'm trying to modify a variable from a form. I want to get rid of any "," but keep the "." while changing it to "%2e"

$price = '6,000.65';

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

echo $price;


This is the exact result from your question:

$price = str_replace(',', '', $price);
$price = str_replace('.', '%2e', $price);
echo $price;

But why would you urlencode it...? If you want to strip unallowed characters (everything but digits and a dot), use the next function:

$price = preg_replace('/[^0-9.]/', '', $price);
// OP requested it...
$price = str_replace('.', '%2e', $price);
echo $price;

Alternatively, you can convert the string into a floating point number and use number_format() to format it nicely.

// 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;

Third option, works in a similar way. % is a special character for sprintf, marking a conversation specification. .2 tells it to have two decimals and f tells it's a floating point number.

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

References:

  • http://php.net/str-replace
  • http://php.net/preg-replace
  • http://php.net/number-format
  • http://php.net/sprintf
  • http://php.net/printf


http://php.net/manual/en/function.str-replace.php

$newPhrase = str_replace($findWhat, $replaceWith, $searchWhere);

so in your case:

$newPrice = str_replace(",", "", $price);


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

$price = urlencode($price);
0

精彩评论

暂无评论...
验证码 换一张
取 消