Reputation: 6549
Is there a way in PHP to only echo the integers from a variable?
For example say I had this piece of code:
$variable = "something123";
How would I echo out only the "123"?
Upvotes: 0
Views: 299
Reputation: 191839
Regular expressions are too fast and too simple in this case.
implode(array_intersect(str_split($variable), range(0,9)));
Upvotes: 0
Reputation: 3550
I'd use preg_replace
$variable = "something123";
echo preg_replace('/[^\d]/','', $variable);
Upvotes: 0
Reputation: 47776
You could use a regex and replace everything that isn't a number by an empty string, thus leaving only numbers:
<?php
$variable = 'something123';
$numbers = preg_replace('/[^0-9]/', '', $variable);
echo $numbers;
?>
http://codepad.viper-7.com/xeNUDk
Note that this might not work with more complicated cases such as multiple number groups separated by other characters. If you need support for that, comment with more details and I'll see what can be done.
Upvotes: 0
Reputation: 8368
You should use a regular expression for this.
preg_match('/\d+/', $variable, $match);
echo $match[0];
The $match
variable is filled with the first numerical part of the string you pass to the preg_match
function.
\d+
means "1 or more digits"
Upvotes: 1