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.
in this article to help you add a space every next 4 characters using PHP.
We will do it using two different methods:
str_split()
and implode()
functions.wordwrap()
function.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
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
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
https://www.php.net/manual/en/function.wordwrap.php
This tutorial helps integrate a PHP SDK with Laravel. We'll install aws-php-sdk into laravel application and access all aws services… Read More
in this quick PHP tutorial, We'll discuss php_eol with examples. PHP_EOL is a predefined constant in PHP and represents an… Read More
This Laravel tutorial helps to understand table Relationships using Elequonte ORM. We'll explore laravel table Relationships usage and best practices… Read More
We'll explore different join methods of Laravel eloquent with examples. The join helps to fetch the data from multiple database… Read More
in this Laravel tutorial, We'll explore valet, which is a development environment for macOS minimalists. It's a lightweight Laravel development… Read More
I'll go through how to use soft delete in Laravel 10 in this post. The soft deletes are a method… Read More