Kathmandu,Nepal
Kathmandu,Nepal

Insert a dash after every nth character in PHP string

We will do it using two different methods:

  1. Using str_split() and implode() functions.
  2. Using wordwrap() function.

1. Using str_split() and implode() functions

The str_split() function use to split string into an array of equal length substrings.

<?php
$string = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
$myarray = str_split($string, 4);
echo implode("-", $myarray);
?>

Output:
ABCD-EFGH-IJKL-MNOP-QRST-UVWX-YZ

Note: Join is an alias of Implode. If you want you can as well use join() in the place of implode().

2.Using wordwrap() function.

The wordwrap() function allows adding of character(s) to a string at regular intervals after a specific length

<?php
echo wordwrap('123456789123456789', 3, "-", true);
?>
Output:
123-456-789-123-456-789

Leave a Comment

Your email address will not be published. Required fields are marked *

×