PHP: Remove all Characters from String except Numbers
Question by Guest | Last update on 2021-07-02 | Created on 2012-07-18
I want to remove any characters that are not numbers/digits from a string in my PHP code. So letters, special characters, spaces, everything out. Can someone help me?
Related Topics
PHP: Remove arbitrary Characters at the Beginning and the End of a String
Tutorial | 0 Comments
PHP: Check Strings with Ctype-Functions for Character Classes
Article | 0 Comments
MySQL: Line Breaks in MySQL
Tip | 0 Comments
Textarea Maxlength: Limit Maximum Number of Characters in Textarea
Tutorial | 3 Comments
PHP: Get first Digit of Number or String
Tutorial | 0 Comments
JavaScript: Remove last character from string
Tip | 5 Comments
Important Note
Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.
Participate
Ask your own question or write your own article on askingbox.com. That’s how it’s done.
That is not difficult, just use the following function for this:
Explanation: First, we have a string $s containing all kinds of characters. Then we use the preg_replace function, with which we can perform replacements with the help of regular expressions. The function excepts 3 parameters: What we are looking for, with which we want to replace and the input string.
We are looking for all characters that are not numbers, so we negate the set of numbers 0 to 9 ([^0-9]) as regular expression and replace all occurrences with an empty string (''). As input and third parameter, we are using our string $s from the beginning.
In the third line, we see our result: Only the numbers from the input string remained.
Last update on 2021-07-02 | Created on 2012-07-20