php-regexHow to get only numbers from a string using regex in PHP?
Using regex in PHP to get only numbers from a string is a simple task. The following example code block uses the preg_match_all
function to extract all numbers from a string:
$string = 'This is a string with some numbers: 1, 2, 3, 4, 5';
preg_match_all('/\d+/', $string, $matches);
print_r($matches);
The output of the above code will be:
Array
(
[0] => Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
)
)
Code explanation
-
$string = 'This is a string with some numbers: 1, 2, 3, 4, 5';
- This is the string from which the numbers will be extracted. -
preg_match_all('/\d+/', $string, $matches);
- This is thepreg_match_all
function which is used to extract all numbers from the string. The\d+
is the regex pattern which matches all numbers. -
print_r($matches);
- This is used to print the extracted numbers.
Helpful links
More of Php Regex
- How to use PHP regex to match a nbsp HTML whitespace?
- How to use PHP regex to match a multiline?
- How to match a quotation mark in PHP regex?
- How to get last matched occurrence in PHP regex?
- How to match a single quote in PHP regex?
- How to use PHP regex to get a YouTube video ID?
- How to use PHP regex to match special characters?
- How to use PHP regex to match a zip code?
- How to use PHP regex to match a year?
- How to match a space using PHP regex?
See more codes...