Using filter_var() method
We can use the filter_var()
method which filters a variable based on supplied filter flag or ID. To extract numbers from the string variable, we can pass the FILTER_SANITIZE_NUMBER_INT
id.
Let’s see an example using this method.
1 2 3 4 5 6 |
<?php $string = 'Welcome to the 0045 and the 456 arena'; $int = filter_var($string, FILTER_SANITIZE_NUMBER_INT); echo $int; |
1 2 3 |
0045456 |
This approach isn’t efficient for certain use case, and simply returns the numbers present within the string together. For a more efficient, we can rely on regular expression.
Use preg_match_all() method
Use preg_match_all()
method with /[0-9]+/
to extract numbers from String in PHP.
1 2 3 4 5 6 |
$string = "Welcome to the 0045 and the 456 arena"; preg_match_all('/[0-9]+/', $string, $matches); print_r($matches); |
1 2 3 4 5 6 7 8 9 10 11 |
Array ( [0] => Array ( [0] => 0045 [1] => 456 ) ) |
Here, output is array of matches, which can then be used to extract the numbers from the string.
We used the preg_match_all()
function to search for the regular expression and extracted the numbers from the string.
We used regular expression in the form of a pattern /[0-9]+/
that matched the numbers in the string.
preg_match_all performs global regular expression match. It takes three arguments:
$pattern
: The pattern to be searched
$subject
: Input String
$matches
:Array of all matches in the String.
Use preg_replace()
method
We can achieve the same output as the filter_var
method using regular expression where we replace all the characters that are not numbers with empty whitespace. The regular expression match value would be /[^0-9]/
.
Let’s illustrate this approach on the same string as in the previous section.
1 2 3 4 5 |
$string = 'Welcome to the 0045 and the 456 arena'; $int = preg_replace('/[^0-9]/', '', $string); echo $int; |
1 2 3 |
0045456 |
preg_replace() performs global regular expression match. It takes three arguments:
$pattern
: The pattern to be searched
$replacement
: the string to replace with searched string
$subject
: Input String