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_allfunction 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 zip code?
- How to use PHP regex to match an exact string?
- How to use regex in PHP to validate an email address?
- How to remove a tag from a string using PHP regex?
- How to use regex in PHP to match any character including newline?
- How to use PHP regex to get a YouTube video ID?
- How to use PHP regex with the "x" modifier?
- How to match a quotation mark in PHP regex?
- How to use PHP regex to match UUID?
- How to match a double quote in PHP regex?
See more codes...