问题
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