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;
}
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.
Use this regular expression !\\d!
<?php
$string = "Hello! 123 How Are You? 456";
preg_match_all('!\d!', $string, $matches);
echo (int)implode('',$matches[0]);
$str = 'In My Cart : 11 items';
$int = (int) filter_var($str, FILTER_SANITIZE_NUMBER_INT);
<?php
$string = "ABC100";
preg_match_all('!\d+!', $string, $matches);
$number = $matches[0][0];
echo $number;
?>
Output: 100
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.