如何将带有数字和空格的字符串转换为int
我有一个小问题。我正在尝试将“1 234”这样的字符串转换为数字:1234 我去不了那里。该字符串是从网站上抓取的。那里可能没有空间吗?因为我已经尝试过 str_replace 和 preg_split 等方法来获取空间,但什么也没有。另外 (int)$abc 仅采用第一个数字 (1)。 如果有人有想法,我会很高兴!谢谢你!
I have a small problem. I am tryng to convert a string like "1 234" to a number:1234
I cant't get there. The string is scraped fro a website. It is possible not to be a space there? Because I've tried methods like str_replace and preg_split for space and nothing. Also (int)$abc takes only the first digit(1).
If anyone has an ideea, I'd be greatefull! Thank you!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
我刚刚遇到了同样的问题,但是提供的答案并没有涵盖我遇到的所有不同情况...
所以我做了这个函数(感谢 Dan,这个想法突然出现在我的脑海中):
所以,基本上,该函数提取字符串中包含的所有数字,无论有多少文本,识别小数分隔符并将每个提取的数字作为浮点数返回。
您可以使用 $decimalSeparator 参数指定自己所在国家/地区使用哪种小数分隔符。
I've just came into the same issue, however the answer that was provided wasn't covering all the different cases I had...
So I made this function (the idea popped in my mind thanks to Dan) :
So, basically, this function extracts all the numbers contained inside of a string, no matter how many text there is, identifies the decimal separator and returns every extracted number as a float.
One can specify what decimal separator is used in one's country with the $decimalSeparator parameter.
使用此代码删除任何其他字符,例如
.,:"'\/
,!@#$%^&*()
,az
>,AZ
:Use this code for removing any other characters like
.,:"'\/
,!@#$%^&*()
,a-z
,A-Z
:我就是这样处理的...
This is how I would handle it...
抓取网站总是需要特定的代码,您知道如何接收输入 - 并且您编写使其可用所需的代码。
这就是为什么第一个答案仍然是str_replace。
Scraping websites always requires specific code, you know how you receive the input - and you write code that is required to make it usable.
That is why first answer is still str_replace.