PHP / Zend: how to remove all characters from a string and save only numbers

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

For instance:

input: +012-(34).56.(ASD)+:"{}|78*9 output: 0123456789 
+4
source share
2 answers

With Zend_Filter_Digits

Returns the value of the string $, deleting all characters except numbers.

Example with a static call through Zend_Filter:

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

Example with an instance of numbers

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

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

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

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

+6
source

Here's how to do it in the general case:

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

Conclusion:

 0123456789 
+11
source

Source: https://habr.com/ru/post/1306891/


All Articles