Search code examples
phpregexdelimiter

Inject a delimiter between sets of N characters in a string


I want to know is there any way to add mid-string delimiters in text like this:

123456789 into 123-456-789

Basically, add "-" between every 3 characters?

Also if the text is

  • ABCDEFGHI
  • A1B2C3D4E
  • or any other format without any space between the characters

Solution

  • <?php
    $i = '123456789';
    echo 'result: ', wordwrap($i, 3, '-', true);
    prints
    result: 123-456-789

    see http://php.net/wordwrap