Friday, April 26, 2024
HomePHPPHP Insert Area Each n Characters

PHP Insert Area Each n Characters


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

S45F-TG677-T56F-8FTG-H56F

Instance 2: Photoshop Key

5674-1111-7888-4446-8888-9999

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.
  • Utilizing wordwrap() perform.

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.

Output:

Array ( 
[0] => DE5R 
[1] => F55D 
[2] => SFR6 
[3] => 79HU 
[4] => 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.

Sponsored Hyperlinks

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

Output:

DE5R-F55D-SFR6-79HU-JN88

Utilizing wordwrap() perform

We are able to additionally obtain similar output utilizing Wordwrap methodology.

The wordwrap() perform permits including of character(s) to a string at common intervals after a particular size.

Syntax:

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 )

Output:

DE5R F55D SFR6 79HU JN88

Add a hyphen after each fourth digit, and the area for a hyphen:

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

Output:

DE5R-F55D-SFR6-79HU-JN88

References:

https://www.php.web/handbook/en/perform.wordwrap.php

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments