codedude
codedude

Reputation: 6549

Only echo integers

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

Answers (5)

Explosion Pills
Explosion Pills

Reputation: 191839

Regular expressions are too fast and too simple in this case.

implode(array_intersect(str_split($variable), range(0,9)));

Upvotes: 0

Evan Davis
Evan Davis

Reputation: 36622

echo preg_replace('/[^0-9]/','', $variable);

Upvotes: 1

Jason Brumwell
Jason Brumwell

Reputation: 3550

I'd use preg_replace

$variable = "something123";

echo preg_replace('/[^\d]/','', $variable);

Upvotes: 0

Alex Turpin
Alex Turpin

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

J. K.
J. K.

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

Related Questions