a1anm
a1anm

Reputation: 1629

PHP RegEx - Get All Digits

I have this code:

$string = "123456ABcd9999"; 
$answer = ereg("([0-9]*)", $string, $digits); 
echo $digits[0]; 

This outputs '123456'. I'd like it to output '1234569999' ie. all the digits. How can I achieve this. I've been trying lots of different regex things but can't figure it out.

Upvotes: 3

Views: 4586

Answers (2)

ircmaxell
ircmaxell

Reputation: 165201

First, don't use ereg (it's deprecated). Secondly, why not replace it out:

$answer = preg_replace('#\D#', '', $string);

Note that \D is the inverse of \d. So \d matches all decimal numeric characters (0-9), therefore \D matches anything that \d does not match...

Upvotes: 15

Lauri Lehtinen
Lauri Lehtinen

Reputation: 10857

You could use preg_replace for this, preg_replace("/[^0-9]/", "", $string) for example.

Upvotes: 7

Related Questions