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

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

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

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

12-27-2010, 07:29 AM

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

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;

12-27-2010, 06:51 PM

// 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 );

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]


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. ;)

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