Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Put dash between every third character

I had a problem on how to put dash in every 3rd character. For example, I want

ABCDEF turn into ABC-DEF

I have this code:

$string = 'ABCDEF';
echo substr_replace(chunk_split($string,3),'-','3','2');
// the output is ABC-DEF

However this code does not work if I add more characters to the $string variable such as ABCDEFGHI. If I use the above code, the output will be:

ABC-DEF GHI
like image 999
softboxkid Avatar asked Dec 08 '11 02:12

softboxkid


2 Answers

You should use PHP's str_split and implode functions.

function hyphenate($str) {
    return implode("-", str_split($str, 3));
}

echo hyphenate("ABCDEF");       // prints ABC-DEF
echo hyphenate("ABCDEFGHI");    // prints ABC-DEF-GHI
echo hyphenate("ABCDEFGHIJKL"); // prints ABC-DEF-GHI-JKL

See http://ideone.com/z7epZ for a working sample of this.

like image 144
Jon Newmuis Avatar answered Sep 22 '22 18:09

Jon Newmuis


Simply:

join('-', str_split($str, 3))
like image 32
deceze Avatar answered Sep 20 '22 18:09

deceze