php get number from string code example
Example 1: php get only numbers from string
$str = 'In My Cart : 11 items';
$int = (int) filter_var($str, FILTER_SANITIZE_NUMBER_INT);
Example 2: convert string to int php
s = "123";
echo intval(s);
s = "hello";
echo intval(s);
Example 3: cast string to int php
$num = "3.14";
$int = (int)$num;
$float = (float)$num;
Example 4: Extract Numbers From a String in PHP
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 \n");
?>
Example 5: Extract Numbers From a String in PHP
phpCopy<?php
$string = 'Sarah has 4 dolls and 6 bunnies.';
$outputString = preg_replace('/[^0-9]/', '', $string);
echo("The extracted numbers are: $outputString \n");
?>
Example 6: Extract Numbers From a String in PHP
phpCopy<?php
$string = 'Sarah has 4 dolls and 6 bunnies.';
preg_match_all('!\d+!', $string, $matches);
print_r($matches);
?>