p2p.wrox.com Forums

Need to download code?

View our list of code downloads.


  Return to Index  

beginning_php thread: Stripping alfabethical chars


Message #1 by "Gerry Vandermaesen" <gerry@a...> on Tue, 29 Oct 2002 19:09:21 +0100
Maybe a silly question, but I don't seem to be able to find the answer
in the online manual. How can I strip all chars from a string except
numbers?

For example, 217.11.35 should return 2171135.

Thanks for the input.

Gerry.

Message #2 by "Gerry Vandermaesen" <gerry@a...> on Tue, 29 Oct 2002 19:34:47 +0100
Nevermind, didn't hear about the regexps functions before.

ereg_replace('[^0-9]', '', $string) did the trick.

-----Original Message-----
From: Gerry Vandermaesen [mailto:gerry@a...] 
Sent: dinsdag 29 oktober 2002 19:09
To: beginning php
Subject: [beginning_php] Stripping alfabethical chars


Maybe a silly question, but I don't seem to be able to find the answer
in the online manual. How can I strip all chars from a string except
numbers?

For example, 217.11.35 should return 2171135.

Thanks for the input.

Gerry.




Message #3 by "Nikolai Devereaux" <yomama@u...> on Tue, 29 Oct 2002 10:38:43 -0800
I guess there's a few ways of doing it.

You can iterate across all characters of the string and check to see if it's a
digit or not.

function is_digit($char)
{
   return ($char > '0') && ($char < '9');
}


$str = '217.11.35';
$all_digits = '';

for($i = 0; $i < strlen($str); ++$i)
{
   if(is_digit($str[$i]))
   {
      $all_digits .= $str[$i];
   }
}



You can also use regular expression functions to split the string by all
non-digit sections and join the digit pieces back together.

$all_digits = join('', preg_split('/[^\d]+/', $str));

What's nice about the preg_split method is that you can just assign the
all-digit version back to $str.

$str = join('', preg_split(.., $str));


Take care,

nik

Message #4 by "Nikolai Devereaux" <yomama@u...> on Tue, 29 Oct 2002 10:40:22 -0800
DOH!  I need coffee.  And there I was thinking I was clever using split and
join on the same line, when a single function did it faster!

I'd recommend using preg_replace, though -- it's generally faster than the ereg
functions.

$str = preg_replace('/[^\d]/', '', $str);


nik


  Return to Index