Get Digits

Any questions involving matching text strings to patterns - the pattern is called a "regular expression."

Moderator: General Moderators

Post Reply
User avatar
MathewByrne
Forum Commoner
Posts: 38
Joined: Sat Mar 27, 2004 9:49 pm
Location: Australia

Get Digits

Post by MathewByrne »

Hi,

I was wondering if anyone could help me with a function that strips all the digits from a string and returns them. Something like this:

Code: Select all

$input = "(04) 854 00912";
echo getDigit($input);
// Would print 0485400912
User avatar
hawleyjr
BeerMod
Posts: 2170
Joined: Tue Jan 13, 2004 4:58 pm
Location: Jax FL & Spokane WA USA

Post by hawleyjr »

Code: Select all

/*
	REMOVE ANY NON 0-9 CHAR
	IF RETURN_INT IS TRUE
	RETURN THE INT VALUE
	SO 2A.3 WOULD RETURN 2
*/
function removeAllNonNumericChar($num,$return_int){
	$num = preg_replace('#[^\d\.]#','',$num);
	
	if($return_int && !ctype_digit($num) && strpos($num,'.') > 0){
		$num = substr($num."",0,strpos($num,'.'));
	}
	return $num;	
	
}
User avatar
MathewByrne
Forum Commoner
Posts: 38
Joined: Sat Mar 27, 2004 9:49 pm
Location: Australia

Post by MathewByrne »

Thanks a heap
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Post by Chris Corbyn »

Moved to regex.
Post Reply