PHP chunk_split() Function
Topic: PHP String ReferencePrev|Next
Description
The chunk_split() function splits a string into smaller chunks or parts.
This function does not modify the original string, it simply returns the chunked string.
The following table summarizes the technical details of this function.
| Return Value: | Returns the chunked string. |
|---|---|
| Version: | PHP 4+ |
Syntax
The basic syntax of the chunk_split() function is given with:
The following example shows the chunk_split() function in action.
Example
Run this code »<?php
// Sample string
$str = "airplane";
/* Returns a string with a period symbol
placed after every two characters */
echo chunk_split($str, 2, ".");
?>
Parameters
The chunk_split() function accepts the following parameters.
| Parameter | Description |
|---|---|
| string | Required. Specifies the string to be chunked. |
| length | Optional. Specifies the chunk length in number. Default is 76 |
| separator | Optional. Specifies a string to be placed at the end of each chunk. Default is \r\n |
More Examples
Here're some more examples showing how chunk_split() function actually works:
If chunk length is greater than the length of the string, then separator is inserted at the end.
Example
Run this code »<?php
// Sample string
$str = "alligator";
// Splitting string into chunks
echo chunk_split($str, 15, "_#_");
?>
If you want string without the separator at the end you could do something like this:
Example
Run this code »<?php
// Sample string
$str = "alligator";
// Removing the last string added
echo substr(chunk_split($str, 2, "_#_"), 0, -3)."<br>";
echo substr(chunk_split($str, 2, "."), 0, -1);
?>

