Using PHP chunk_split() to Split Strings into Chunks
This article explains the PHP chunk_split() function, its syntax, parameters, return value, and provides two practical code examples that demonstrate how to split strings into fixed‑size chunks with custom end characters.
The chunk_split() function in PHP splits a string into smaller chunks, optionally inserting a specified end sequence after each chunk. It is useful for formatting outputs such as base64‑encoded data to comply with RFC 2045.
Syntax :
string chunk_split(string $body, int $chunklen = 76, string $end = "\r\n")Parameters :
$body – the string to be split.
$chunklen – the length of each chunk.
$end – the sequence appended after each chunk.
Return value : the resulting string after being split according to the given parameters.
Example 1 – split a short sentence into chunks of six characters, using "..." as the end marker:
<?php
$str = "Hello world!";
echo chunk_split($str, 6, "...");
?>Output :
Hello ...world!...Example 2 – split a word into single‑character chunks, using a period as the end marker:
<?php
$str = "Shanghai";
echo chunk_split($str, 1, ".");
?>Output :
S.h.a.n.g.h.a.i.Laravel Tech Community
Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.