How to insert a dash after every nth character in PHP string
  John Mwaniki /   21 Oct 2021

How to insert a dash after every nth character in PHP string

You most likely have seen long strings of characters formatted in a pattern where there are spaces or dashes at equal intervals after a specific number of characters. Such strings may be numeric, alphabetical, or alphanumeric.

Examples of such strings are the software product activation keys, or electricity prepared token numbers

Example 1: Windows Product Key

W269N-WFGWX-YVC9B-4J6C9-T83GX

Example 2: Photoshop CC serial key

1045-1656-1984-6490-5561-5688

Example 3: Electricity prepaid token number

6664-1046-1710-0096-8674

Example 4: Kaspersky security key

CXWPP-HYMRP-VBSPP-TP787

Kindly note that the above are not usable keys but just for demonstration purposes on the common formatting.

Without dashes in them, the above codes will be very difficult to read. The dashes or spaces in between helps improve readability instead of seeing the code as a long block of text.

I have severally been asked by fellow developers how to format strings in such a way. I too some time back faced challenges when I wanted to do such formatting for the very first time.

For that reason, I am writing this article to help you who could be wondering how to do it. We will be doing it using PHP in this article.

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

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

<?php
$string = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
print_r(str_split($string, 4));
?>

Output:

Array (
  [0] => ABCD
  [1] => EFGH
  [2] => IJKL
  [3] => MNOP
  [4] => QRST
  [5] => UVWX
  [6] => YZ
)

Explanation


str_split($string, 4)

From our example above, the str_split() takes two arguments. The first is the string we want to split, and the second is the length of each of the substrings/array elements that we want to split our string into.

In our case, we have used the alphabets as our string ($string) and 4 as the length of substrings. As you can see from the output above, we have formed an array with each index having a value of 4 characters apart from the last index as we have not more characters to make them four.

In our example, since we have split the string after every 4th character, we will add the hyphen/dash after every fourth character. You can use any other length such as 2, 3, 5, etc depending on where you want to insert your dash as long as that length you choose does not exceed the string length.

In case you don't specify the length in the str_split() function and pass the string as the only argument, the string will be split after every character by default.

The next step will be to convert the array back into a string, this time adding a dash after the fourth character.

To achieve that, we will use the implode() function.

We will pass two arguments to it. The first specifies which character we want to insert into the new string, and the second is the array.

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

Output:

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

We can shorten the above to one line as below and the output will be the same.

<?php
echo implode("-", str_split("ABCDEFGHIJKLMNOPQRSTUVWXYZ", 4));
?>

To format your string, all you need is to replace the alphabets with your string of characters(which could be numeric, alphanumeric or alphabetical), and then replace 4 with the interval in which you want to insert a dash.

If you want to insert a space or a different character instead of a dash, just replace the dash in the implode() function within the quotes.

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

Using wordwrap() function.

This is actually the simplest way of formating the string with dashes at regular intervals.

The wordwrap() function allows adding of character(s) to a string at regular intervals after a specific length as in the example below. In our example, we will add a dash after every 3 characters in a numeric string.

<?php
echo wordwrap('123456789123456789', 3, "-", true);
?>

Output:

123-456-789-123-456-789

You should pass 4 arguments to the wordwrap() function. The first should be the actual string, the second the length in which we want to add the character(s) after, the third is the character in which we want to insert into the string while the fourth should be set to true.

That's it for now!