PHP - chunk_split() Function
The PHP chunk_split() function is used to split a string into series of smaller chunks of the specified length. The "chunks" refer to a smaller part of a string, which can consist of a single character, double characters, or multiple characters.
This function accepts a parameter named "separator", which is inserted after every specified length of characters.
Syntax
Following is the syntax of the PHP chunk_split() function −
chunk_split(string $str, int $length = 76, string $sepa = "\r\n"): string
Parameters
Following are the parameters of this function −
- str − The string to be chunked.
- length − The length of each chunk. The default length is 76.
- sepa − The string is used to separate the chunks, which can be a line-ending sequence or any other string.
Return Value
This function returns the chunked string.
Example 1
The following is the basic example of the PHP chunk_split() function −
<?php $str = "Tutorialspoint"; echo "The string to be chunked: $str"; $length = 1; $separator = "."; echo "\nThe chunk length: $length"; echo "\nSeparator: $separator"; echo "\nThe chunked string: ".chunk_split($str,$length,$separator); ?>
Output
The above program produces the following output −
The string to be chunked: Tutorialspoint The chunk length: 1 Separator: . The chunked string: T.u.t.o.r.i.a.l.s.p.o.i.n.t.
Example 2
If the chunk length is greater than 0, the string will be split into smaller chunks of the specified length.
Following is another example of the PHP chunk_split() function. We use this function to split this string "Chunked String" into smaller chunks of the specified length 2 −
<?php $str = "Chunked String"; echo "The string to be chunked: $str"; $length = 2; $separator = "/"; echo "\nThe chunk length: $length"; echo "\nSeparator: $separator"; echo "\nThe chunked string: ".chunk_split($str,$length,$separator); ?>
Output
Once the above program is executed, the following output will be displayed −
The string to be chunked: Chunked String The chunk length: 2 Separator: / The chunked string: Ch/un/ke/d /St/ri/ng/
Example 3
If the "separator" parameter is omitted, the PHP chunk_split() function splits (chunks) the string into smaller chunks and separates them using the default value "\n" −
<?php $str = "Hello World"; echo "The string to be chunked: $str"; $length = 1; #$separator = "@tp"; echo "\nThe chunk length: $length"; #echo "\nSeparator: $separator"; echo "\nThe chunked string: ".chunk_split($str,$length); ?>
Output
Following is the output of the above program −
The string to be chunked: Hello World The chunk length: 1 The chunked string: H e l l o W o r l d