Suppose, I have this string:
$string = "Hello! 123 How Are You? 456";
I want to set variable $int
to $int = 123456;
How do I do it?
Example 2:
$string = "12,456";
Required:
$num = 12456;
Thank you!
Suppose, I have this string:
$string = "Hello! 123 How Are You? 456";
I want to set variable $int
to $int = 123456;
How do I do it?
Example 2:
$string = "12,456";
Required:
$num = 12456;
Thank you!
Correct variant will be:
$string = "Hello! 123 How Are You? 456";
$int = intval(preg_replace('/[^0-9]+/', '', $string), 10);
You can use this method to select only digit present in your text
function returnDecimal($text) {
$tmp = "";
for($text as $key => $val) {
if($val >= 0 && $val <= 9){
$tmp .= $val
}
}
return $tmp;
}
Use this regular expression !\d!
<?php
$string = "Hello! 123 How Are You? 456";
preg_match_all('!\d!', $string, $matches);
echo (int)implode('',$matches[0]);
You can use the below:
$array = [];
preg_match_all('/-?\d+(?:\.\d+)?+/', $string, $array);
Where $string is the entered string and $array is where each number(not digit!,including also negative values!) is loaded and available for different more operations.
<?php
$string = "ABC100";
preg_match_all('!\d+!', $string, $matches);
$number = $matches[0][0];
echo $number;
?>
Output: 100