问题
I'm trying to remove all non-numeric characters from a string. This is the string:
$price = '₪1,180.00';
(the first character is the new israeli shekel currency symbol)
I tried to use:
$price_numeric_value = preg_replace( '/\D/', '', $price );
echo '<pre>';var_dump( $price_numeric_value );echo '</pre>';
$price_numeric_value = preg_replace( '~\D~', '', $price );
echo '<pre>';var_dump( $price_numeric_value );echo '</pre>';
$price_numeric_value = preg_replace( '/[^0-9.]/', '', $price );
echo '<pre>';var_dump( $price_numeric_value );echo '</pre>';
As suggested in these posts:
https://stackoverflow.com/a/34399544/4711865
https://stackoverflow.com/a/33993704/4711865
The output i'm getting is this:
string(10) "8362118000"
Any idea why?
EDIT: I'm running this code on a Wordpress website, the php file is encoded in utf-8 and adding header('Content-Type: text/html; charset=utf-8');
doesn't help.
回答1:
8362
is the numeric part of the html entity for the New Sheqel Sign ₪
, when you remove all non numeric you got 8362
just before the value.
You have to decode the string before preg_replace.
$price_numeric_value = preg_replace( '/\D/', '', html_entity_decode($price) );
echo $price_numeric_value;
来源:https://stackoverflow.com/questions/53283229/remove-all-non-numeric-characters-from-a-string-in-php