How to remove all characters exept numbers from a string using PHP

H

How Can We Help?

How to remove all characters exept numbers from a string using PHP

This is really easy, we will make use of the preg_replace PHP Function which is 100% compatible with PHP 5.3

Example: 

$string = 'This is my phone number: +28 (0)212 1234!!! '
 
$numberString = preg_replace('[\D]', '', $string);
 
echo $numberString; //Will output 2802121234

This is a good way to format phone numbers etc.

The regular expression character \D means to match a character that’s not a digit

About the author

Ian Carnaghan

I am a software developer and online educator who likes to keep up with all the latest in technology. I also manage cloud infrastructure, continuous monitoring, DevOps processes, security, and continuous integration and deployment.

About Author

Ian Carnaghan

I am a software developer and online educator who likes to keep up with all the latest in technology. I also manage cloud infrastructure, continuous monitoring, DevOps processes, security, and continuous integration and deployment.

Follow Me