Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP/Zend: How to remove all chars from a string and keep only numbers

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

For example:

input: +012-(34).56.(ASD)+:"{}|78*9
output: 0123456789
like image 226
Awan Avatar asked Dec 03 '22 12:12

Awan


2 Answers

This is how to do that generically:

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

Output:

0123456789
like image 177
Sarfraz Avatar answered Dec 28 '22 22:12

Sarfraz


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

like image 45
Gordon Avatar answered Dec 28 '22 23:12

Gordon