22 Votes

PHP: Remove all characters from string except numbers

Question by Guest | 2012-07-18 at 17:09

I want to remove from a string in PHP any characters that are not numbers. So letters, special characters, spaces, everything out. Can someone help me?

8Best Answer10 Votes

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

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

Explanation: First, we have a string $s containing all kinds of characters. The function preg_replace, we are using, 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]) and replace all occurrences with an empty string (''). As input, we are using our string $s. In the third line, we see our result: Only the numbers from the input string remained.
2012-07-20 at 11:30

ReplyPositive Negative

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.


Ask your own question or write your own article on askingbox.com. That’s how it’s done.