...

View Full Version : echo numeric characters ONLY in a string?



DataTalk
12-26-2010, 08:00 PM
Could someone help with this?

for this line of text charactors and numbers;
Company (100)

how would I write code to echo "only numeric values";

result = 100

DJCMBear
12-26-2010, 08:42 PM
Try this out.


$str = "int(11)";
print preg_replace("/([^0-9]+)/","",$str);

kbluhm
12-27-2010, 07:29 AM
Or:


// remove non-numeric characters
$string = preg_replace( '/\D/', '', $string );

DataTalk
12-27-2010, 05:15 PM
Thanks DJCMBear! your suggestion worked in my example....

kbluhm: not sure how your suggestion would apply to this, and will that code remove any and all chatacters other other than numeric?



$str = $columns[Type];
$size = preg_replace("/([^0-9]+)/","",$str);
echo $size;

DJCMBear
12-27-2010, 06:51 PM
Or:


// remove non-numeric characters
$string = preg_replace( '/\D/', '', $string );


Wouldn't it be this, saying if now digit?
As currently it looks like it's setting all digits to nothing, not 100% sure though.
// remove non-numeric characters
$string = preg_replace( '/^\D/', '', $string );

kbluhm
12-27-2010, 08:25 PM
No, that's wrong. In the above example, the ^ signifies the beginning of the string in that context, so it will remove the first character from the beginning of the string... only if is a non-digit.

\d is a digit, equivalent to [0-9]
\D is a non-digit, equivalent to [^0-9]

Just as:
\w is a word character, equivalent to [A-Za-z0-9_]
\W is a non-word character, equivalent to [^A-Za-z0-9_]
\s is a whitespace character
\S is a non-whitespace character, equivalent to [^\s]

...etc.

So, yes DataTalk, the following code will remove all non-digits from the string:


$string = preg_replace( '/\D/', '', $string );

The original suggestion will work, I just provided a simpler alternative. Learning the ins-and-outs of PCRE will take you a long way. ;)

DJCMBear
12-28-2010, 05:28 AM
Ahhhhh sorry I missed the caps lol my bad, I get what it's doing now lol.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum