php php字符串转int

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7008214/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 01:48:05  来源:igfitidea点击:

php string to int

phpstringint

提问by agh

$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.

正如预期的那样,两者都产生 88。有人知道是否有一个字符串到 int 函数可以用于 $b 的值并产生 888888?我在谷歌上搜索了一下,但没有运气。

Thanks

谢谢

回答by Gabi Purcaru

You can remove the spaces before casting to int:

您可以在强制转换为之前删除空格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);

回答by XzKto

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

如果你只想留下数字 - 使用 preg_replace 像:(int)preg_replace("/[^\d]+/","",$b)。

回答by Silfverstrom

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

替换空白字符,然后对其进行转换(使用 intval 函数或通过常规类型转换)

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

回答by Delan Azabani

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

你甚至想要结果是什么?888888?如果是这样,只需删除带有 的空格str_replace,然后进行转换。

回答by Manse

Use str_replaceto remove the spaces first ?

用于str_replace先删除空格?

回答by Fizik26

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

您可以str_replace像这样声明变量 $b 时使用:

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

Or the most beautiful solution is to use intval :

或者最漂亮的解决方案是使用 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.

如果您的值 '88 888' 来自其他变量,只需将 '88 888' 替换为包含您的字符串的变量。