Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Format integer or string in php

sorry for a noob question but I am wondering if you could format strings in php with comma or dashes, something like this:

Ex. #1

Sample Input: 123456789
Formatted Output: 123,456,789 or 123-456-789

Ex. #2

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Sample Input: 0123456789
Formatted Output: 012,3456,789 or 012-3456-789

If anyone could help me out, that would be appreciated.

>Solution :

You could use a regex replacement here:

function formatNum($input, $sep) {
    return preg_replace("/^(\d{3})(\d+)(\d{3})$/", "$1".$sep."$2".$sep."$3", $input);
}

echo formatNum("123456789", ",");   // 123,456,789
echo "\n";
echo formatNum("0123456789", "-");  // 012-3456-789
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading