php string to int

回眸只為那壹抹淺笑 提交于 2020-01-01 07:29:11

问题


$a = '88';
$b = '88 8888';

echo (int)$a;
echo (int)$b;

as expected, both produce 88. Anyone know if there's a string to int function that will work for $b's value and produce 888888? I've googled around a bit with no luck.

Thanks


回答1:


You can remove the spaces before casting to int:

(int)str_replace(' ', '', $b);

Also, if you want to strip other commonly used digit delimiters (such as ,), you can give the function an array (beware though -- in some countries, like mine for example, the comma is used for fraction notation):

(int)str_replace(array(' ', ','), '', $b);



回答2:


If you want to leave only numbers - use preg_replace like: (int)preg_replace("/[^\d]+/","",$b).




回答3:


What do you even want the result to be? 888888? If so, just remove the spaces with str_replace, then convert.




回答4:


Replace the whitespace characters, and then convert it(using the intval function or by regular typecasting)

intval(str_replace(" ", "", $b))



回答5:


Use str_replace to remove the spaces first ?




回答6:


You can use the str_replace when you declare your variable $b like that :

$b = str_replace(" ", "", '88 8888');
echo (int)$b;

Or the most beautiful solution is to use intval :

$b = intval(str_replace(" ", "", '88 8888');
echo $b;

If your value '88 888' is from an other variable, just replace the '88 888' by the variable who contains your String.



来源:https://stackoverflow.com/questions/7008214/php-string-to-int

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