Page 1 of 1

removing characters

Posted: Mon Oct 23, 2006 11:40 am
by iffo
suppose I have something like the following.


$phone="(212)435_7869)"

I want to make sure it has only number nothing else. Is there easy way to do that?
I want it to be like
$phone= 2124357869

Posted: Mon Oct 23, 2006 11:49 am
by Cameri
Try:

Code: Select all

$phone = "(209)45345444";
$length = strlen($phone);
$new_phone = "";
for ($i=0;$i<$length;$i++) {
 if (ord($phone[$i]) >= ord('0') && ord($phone[$i]) <= ord('9'))
  $new_phone .= $phone[$i];
}
echo $new_phone;

Posted: Mon Oct 23, 2006 11:50 am
by hawleyjr
//untested

Code: Select all

$num = preg_replace('#[^\d\.]#','',$num);
Edit:

I just tried this with a decimal and it returned the decimal. If you try my code be sure to test for the decimal.

Posted: Mon Oct 23, 2006 11:54 am
by Cameri
Yeah, your untested version works for me.

Edit: Why would a phone number contain a dot? A extension?

Posted: Mon Oct 23, 2006 11:54 am
by volka
hawleyjr wrote://untested

Code: Select all

$num = preg_replace('#[^\d\.]#','',$num);
\D matches a "non-digit".
and why a dot?
iffo wrote:I want to make sure it has only number nothing else.

Code: Select all

$num = preg_replace('#\D+#','',$num);

Posted: Mon Oct 23, 2006 11:57 am
by hawleyjr
Cameri wrote:Yeah, your untested version works for me.

Edit: Why would a phone number contain a dot? A extension?
I type phone number with dots all the time: 555.555.5555

Posted: Mon Oct 23, 2006 12:11 pm
by iffo
thanks a lot, loop works, preg match will not work, because it could be any character...

Posted: Mon Oct 23, 2006 12:31 pm
by hawleyjr
iffo wrote:thanks a lot, loop works, preg match will not work, because it could be any character...
Did you try volka's modification?

Posted: Mon Oct 23, 2006 12:45 pm
by Cameri
I'm pretty sure volka's is way faster.

Posted: Mon Oct 23, 2006 12:50 pm
by iffo
thanks again. I am trying to understand this

$num = preg_replace('#\D+#','',$num);

you said D replace non-digit
what is # signs for and +

Posted: Mon Oct 23, 2006 1:00 pm
by Cameri
Im not sure about the #'s, but + means one or more of the preceeding match, and since it's \D, it means one or more non-digits.

Posted: Mon Oct 23, 2006 1:17 pm
by volka
You need a delimiter for pcre, perl compatible regular expressions.
That's just a character marking the start and end of a pattern, like " or ' mark the start or end of a string.
Can be / like in perl script sbut can also be #, ! and many more. I usually choose !

Code: Select all

$pattern = '!\D+!';

Posted: Tue Oct 24, 2006 8:42 am
by iffo
$num = preg_replace('#[^\d\.]#','',$num);
means keep dot and digits and replace rest with ''.