If you just want to filter everything other than the numbers out, the easiest is to use filter_var:
$str = 'In My Cart : 11 items';
$int = (int) filter_var($str, FILTER_SANITIZE_NUMBER_INT);
Answer from Daniel Bøndergaard on Stack OverflowIf you just want to filter everything other than the numbers out, the easiest is to use filter_var:
$str = 'In My Cart : 11 items';
$int = (int) filter_var($str, FILTER_SANITIZE_NUMBER_INT);
You can use regex to extract all numeric characters from a string:
$str = 'In My Cart : 11 12 items';
preg_match_all('!\d+!',
matches);
print_r($matches);
You can then concatenate them to make your integer:
$integer = implode('', $matches[0]);
You can make use of regular expressions to first match your pattern of characters (Case#) and then you expect to match numbers only (digits), that is \d in PCRE (Demo):
$numbers = preg_match("/Case#(\d+)/", $text, $matches)
? (int)$matches[1]
: NULL
;
unset($matches);
For multiple (integer) matches at once:
$numbers = preg_match_all("/Case#(\d+)/", $text, $matches)
? array_map('intval', $matches[1])
: NULL
;
unset($matches);
You can locate it as you do it already, and then scan for the number (Demo):
$find = strpos($text, 'Case#');
sscanf(substr($text, $find), 'Case#%d', $numbers);
You can use regular expressions for this. The \d escape sequence will match all digits in the subject string.
For example:
<?php
function get_numerics ($str) {
preg_match_all('/\d+/',
matches);
return $matches[0];
}
$one = 'foo bar 4 baz (5 qux quux)';
three = 'qux bar 12 quux (3 foo)';
$four = 'foo baz 3 bar (13 quux foo)';
print_r(get_numerics($one));
print_r(get_numerics($two));
print_r(get_numerics($three));
print_r(get_numerics($four));
https://3v4l.org/DiDBL
You can do:
$str = 'string that contains numbers';
preg_match_all('!\d+!',
matches);
print_r($matches);
filter_var
You can use filter_var and sanitize the string to only include integers.
$s = "Lesson 001: Complete";
echo filter_var($s, FILTER_SANITIZE_NUMBER_INT);
https://eval.in/309989
preg_match
You can use a regular expression to match only integers.
$s = "Lesson 001: Complete";
preg_match("/([0-9]+)/", $s, $matches);
echo $matches[1];
https://eval.in/309994
you can try with /\d+/
$str = the_title();
preg_match_all('/\d+/', $str, $matches);
echo $matches[0];