2 2 Votes

PHP: Remove all characters from string except numbers

Question by Guest | 18/07/2012 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?

ReplyPositiveNegative

Stefan Trost

Show Profile | Message
Avatar
8Best Answer
10 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. 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.
20/07/2012 at 11:30

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 articles on askingbox.com. How to do.