Home > Back-end >  Format integer or string in php
Format integer or string in php

Time:11-22

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

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

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

CodePudding user response:

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

CodePudding user response:

If it's just a case of split the initial string into 3 char segments and join them with a specific char, you can use str_split() with the number of chars you want in each segment and then implode() the result with the separator you need...

$test = '012345678';

echo implode("-", str_split($test, 3));

CodePudding user response:

    $number = 133456789;
    $number_text = (string)$number; // convert into a string
    if(strlen($number_text) %3 == 0){
        $arr = str_split($number_text, "3"); 
        // $price_new_text = implode(",", $arr);  
        $number_new_text = implode("-", $arr);  
        echo $number_new_text; 
    }
    else{
        
        if(  preg_match( '/(\d{3})(\d{4})(\d{3})$/', $number_text,  $matches ) )
        {
            $number_new_text = $matches[1] . '-' .$matches[2] . '-' . $matches[3];
            $number_new_text = $matches[1] . ',' .$matches[2] . ',' . $matches[3];
            echo $number_new_text;
        }
    }
  • Related