PHP | split a fixed number of characters from the string using chunk_split() function

By IncludeHelp Last updated : December 27, 2023

Problem statement

Given a string and we have to split a fixed number of characters from the string.

Splitting a fixed number of characters from the string

When we need a set of small parts of the string (of a fixed number of characters), we can use chunk_split() function. It returns a defined number of characters from the string and can also add a character or string after the string.

Sample Input/Output

Input:
str = "Hello world!"
//if we want to extract three characters chucks of the string 
//no characters at the end (default \r\n will be added)
Function call: chunk_split(str, 3)
Output:
Hel
lo 
wor
ld!

Input: 
str  = "41424344454647484950"

//If we want to extract two characters chunks of the string 
//with hyphen (-) after the chunks
Function call: chunk_split(str, 2, "-")
Output:
41-42-43-44-45-46-47-48-49-50

PHP script to split a fixed number of characters from the string

<?php
$str = "Hello world!";	
$split_str = chunk_split($str, 3);
echo ("The extracted characters are...\n");
echo ($split_str);

$str = "41424344454647484950";	
$split_str = chunk_split($str, 2, "-");
echo ("The extracted characters are...\n");
echo ($split_str);
?>

Output

The output of the above example is:

The extracted characters are...
Hel
lo 
wor
ld!
The extracted characters are...
41-42-43-44-45-46-47-48-49-50-

To understand the above example, you should have the basic knowledge of the following PHP topics:

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.