phpCopy<?php
$string = 'Sarah has 4 dolls and 6 bunnies.';
$outputString = preg_replace('/[^0-9]/', '', $string);
echo("The extracted numbers are: $outputString
");
?>
$str = 'In My Cart : 11 items';
$int = (int) filter_var($str, FILTER_SANITIZE_NUMBER_INT);
function get_numerics ($str) {
preg_match_all('/d+/', $str, $matches);
return $matches[0];
}
// this function will return an array of number
$str = "3 dogs were running!";
echo (get_numerics($str)[0]);
// output 3
phpCopy<?php
$string = 'Sarah has 4 dolls and 6 bunnies.';
$int = (int) filter_var($string, FILTER_SANITIZE_NUMBER_INT);
echo("The extracted numbers are: $int
");
?>
/*
The PHP is_numeric() function can be used to find whether a variable is
numeric. The function returns true if the variable is a number or a
numeric string, false otherwise.
*/
#How to check if the variable is numeric
<?php
$x = 24523;
var_dump(is_numeric($x));
$x = "24523";
var_dump(is_numeric($x));
$x = "124.14" + 100;
var_dump(is_numeric($x));
$x = "Random Text";
var_dump(is_numeric($x));
?>
/*This outputs
bool(true)
bool(true)
bool(true)
bool(false)
*/
phpCopy<?php
$string = 'Sarah has 4 dolls and 6 bunnies.';
preg_match_all('!d+!', $string, $matches);
print_r($matches);
?>