on this tutorial, we’ll study insert area each n characters. You might have seen lengthy strings of characters formatted in a sample the place areas or dashes at equal intervals after a particular variety of characters.
Instance 1: Home windows Product Key
Instance 2: Photoshop Key
I wish to add an area each subsequent 4 characters.
Add an area each subsequent 4 characters
on this article that can assist you add an area each subsequent 4 characters utilizing PHP.
We are going to do it utilizing two totally different strategies:
Utilizing str_split() and implode() capabilities
We use the
str_split() perform to separate our string into an array of equal size substrings.
<?php $string = "DE5RF55DSFR679HUJN88"; print_r(str_split($string, 4)); ?>
The above code will cut up string into arrays.
Array (  => DE5R  => F55D  => SFR6  => 79HU  => JN88 )
We’ll use the
implode() perform to create a string with separator.
We are going to move two arguments into implode methodology. The primary specifies which character we need to insert into the brand new string, and the second is the array.
<?php $string = "DE5RF55DSFR679HUJN88"; $myarray = str_split($string, 4); echo implode("-", $myarray); ?>
Utilizing wordwrap() perform
We are able to additionally obtain similar output utilizing Wordwrap methodology.
wordwrap() perform permits including of character(s) to a string at common intervals after a particular size.
wordwrap( string $string, int $width = 75, string $break = "n", bool $cut_long_words = false ): string
- The primary param must be the precise string,
- The second argument the size by which we need to add the character(s) after,
- The third is the character by which we need to insert into the string.
- The fourth must be set to true.
Instance : Insert area after fourth character.
echo wordwrap('DE5RF55DSFR679HUJN88' , 4 , ' ' , true )
DE5R F55D SFR6 79HU JN88
Add a hyphen after each fourth digit, and the area for a hyphen:
echo wordwrap('DE5RF55DSFR679HUJN88' , 4 , '-' , true )