35 Votes

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?

ReplyPositiveNegative
9Best Answer11 Votes

That is not difficult, just use the following function for this:

$s = 'aANx182 29 ().';
$s = preg_replace('/[^0-9]/', '', $s);
echo $s;  // 18229

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

ReplyPositive Negative
Reply

Related Topics

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.