Remove all non-numeric characters from a string in PHP

拈花ヽ惹草 提交于 2020-04-18 08:38:14

问题


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 &#8362;, 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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!