Home » PHP

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

Here, we are going to learn how to split a fixed number of characters from the string? It can be done using chunk_split() function.
Submitted by IncludeHelp, on February 03, 2019

Given a string and we have to split 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.

Read more: PHP chunk_split() function

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-





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.



Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.