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

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

Here, we will figure out how to part a fixed number of characters from the string? It tends to be finished utilizing chunk_split() work.

Given a string and we need to part a fixed number of characters from the string.

At the point when we need a lot of little pieces of the string (of a fixed number of characters), we can utilize chunk_split() work. It restores a characterized number of characters from the string and can likewise include a character or string after the string.

Examples:

    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 Code:

<?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 extracted characters are...
Hel
lo 
wor
ld!
The extracted characters are...
41-42-43-44-45-46-47-48-49-50-

Recent Posts

error: Alert: Content is protected!!