PHP Insert Space Every n Characters

in this tutorial, we’ll learn how to insert space every n characters. You have seen long strings of characters formatted in a pattern where spaces or dashes at equal intervals after a specific number of characters.

Example 1: Windows Product Key

S45F-TG677-T56F-8FTG-H56F

Example 2: Photoshop Key

5674-1111-7888-4446-8888-9999

I would like to add a space every next 4 characters.

Add a space every next 4 characters

in this article to help you add a space every next 4 characters using PHP.

We will do it using two different methods:

  • Using str_split() and implode() functions.
  • Using wordwrap() function.

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 = "DE5RF55DSFR679HUJN88";
print_r(str_split($string, 4));
?>

The above code will split string into arrays.

Output:

Array ( 
[0] => DE5R 
[1] => F55D 
[2] => SFR6 
[3] => 79HU 
[4] => JN88 
)

We’ll use the implode() function to create a string with separator.

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

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

Output:

DE5R-F55D-SFR6-79HU-JN88

Using wordwrap() function

We can also achieve same output using Wordwrap method.

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

Syntax:

wordwrap(
    string $string,
    int $width = 75,
    string $break = "\n",
    bool $cut_long_words = false
): string
  • The first param should be the actual string,
  • The second argument 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.
  • The fourth should be set to true.

Example : Insert space after fourth character.

echo wordwrap('DE5RF55DSFR679HUJN88' , 4 , ' ' , true )

Output:

DE5R F55D SFR6 79HU JN88

Add a hyphen after every fourth digit, and the space for a hyphen:

echo wordwrap('DE5RF55DSFR679HUJN88' , 4 , '-' , true )

Output:

DE5R-F55D-SFR6-79HU-JN88

References:

https://www.php.net/manual/en/function.wordwrap.php

Leave a Reply

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