I need some help understanding the trim function. From the docs, its says the following about character_mask:
character_mask Optionally, the stripped characters can also be specified using the character_mask parameter. Simply list all characters that you want to be stripped. With .. you can specify a range of characters.
When I test by specifying trim($num,"$\,")
, its not working as I expected.
$num = '$1,000.00';
$findSymbol = strpos($num, '$'); // find $ symbol
if ($findSymbol === false) {
$num = $num;
}else{
$num = trim($num,"$\,"); // strip the $ and the , symbol
}
var_dump($num); //OUTPUT: 1,000.00
Basically, all I want is strip the $
and the ,
symbols all together so the output would look like this:
1000.00
Any help is greatly appreciated. Thanks!
trim() strips the listed characters from the beginning and/or end of the string as described in the docs you've quoted.
Strip whitespace (or other characters) from the beginning and end of a string
If you want to remove characters from the middle of a string, use str_replace()
$num = str_replace(['$', ','], '', $num);
You can also use the two functions in combination:
$num = str_replace(',', '', trim($num, '$'));
you can do this by removing every character expect allowed(in this case these are 0-9
and .
)
preg_replace("/[^0-9.]/", "", $num );
it will remove all character other than 0-9
and .
$num = '$1,000.00';
echo preg_replace("/[^0-9.]/", "", $num );
1000.00
Use str_replace
$num = '$1,000.00';
$findSymbol = strpos($num, '$'); // find $ symbol
if ($findSymbol === false) {
$num = $num;
}else{
//$num = trim($num,"$\,"); // strip the $ and the , symbol
$num = str_replace(array('$',','), "", $num);
}
var_dump($num); //OUTPUT: 1,000.00
use str_replace
str_replace(",","",str_replace("$","","$1,000.00"))
You can do all in one line with str_replace + array.
echo str_replace(['$', ','], null, '$1,000.00');
1000.00