How to convert a string with numbers and spaces into an int

元气小坏坏 提交于 2019-12-22 08:53:30

问题


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!


回答1:


This is how I would handle it...

<?php

$string = "Here! is some text, and numbers 12 345, and symbols !£$%^&";

$new_string = preg_replace("/[^0-9]/", "", $string);

echo $new_string // Returns 12345

?>



回答2:


intval(preg_replace('/[^0-9]/', '', $input))



回答3:


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.

$iInt = (int)str_replace(array(" ", ".", ","), "", $iInt);



回答4:


$str = "1 234";
$int = intval(str_replace(' ', '', $str)); //1234


来源:https://stackoverflow.com/questions/6307827/how-to-convert-a-string-with-numbers-and-spaces-into-an-int

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