views:

266

answers:

2

I want to keep only numbers and remove all characters from a variable.

For example:

input: +012-(34).56.(ASD)+:"{}|78*9
output: 0123456789
+3  A: 

This is how to do that generically:

$numbers = preg_replace('/[^0-9]+/', '', '+012-(34).56.(ASD)+:"{}|78*9');
echo $numbers;

Output:

0123456789
Sarfraz
I'm not a regexp expert so I assume the + in the matching pattern is for "at least one character" but I don't understand why /[^0-9]/ is not enough. Do you have any example ?
Benjamin Delichère
@Benjamin Delichère: To be more specific, the `+` means `match one or more`. If you used only `/[^0-9]/` it won't match up all the instances that might come in throughout the string you are dealing with.
Sarfraz
it is probably tiny little bit faster.
celalo
+5  A: 

With Zend_Filter_Digits

Returns the string $value, removing all but digit characters.

Example with static call through Zend_Filter:

echo Zend_Filter::filterStatic('abc-123-def-456', 'Digits'); // 123456

Example with Digits instance

$digits = new Zend_Filter_Digits;
echo $digits->filter('abc-123-def-456'); // 123456;

Internally, the filter will use preg_replace to process the input string. Depending on if the Regex Engine is compiled with UTF8 and Unicode enabled, one of these patterns will be used:

  • [^0-9] - Filter if Unicode is disabled
  • [^[:digit:]] - Filter for the value with mbstring
  • [\p{^N}] - Filter for the value without mbstring

See http://framework.zend.com/svn/framework/standard/trunk/library/Zend/Filter/Digits.php

Gordon
Call to undefined method Zend_Filter::filterstatic()......What should I include ?
Awan
@Awan `filterStatic` with a capital S. Also which version of ZF are you using? Note that *prior to the 1.9 release, Zend_Filter allowed the usage of the static get() method. As with release 1.9 this method has been renamed to filterStatic() to be more descriptive. The old get() method is marked as deprecated.* - http://framework.zend.com/manual/en/migration.19.html
Gordon
it is working with get().
Awan