Skip to content
Tutorials Center
My learning

Topics

PHP Reference Β· String Functions

PHP chunk_split() function

Reference for PHP chunk_split(): insert a separator after every N characters, the default CRLF ending, the trailing separator and byte-based splitting.

chunk_split() cuts a string into pieces of a fixed length and puts a separator after each piece. By default the chunk length is 76 and the separator is "\r\n", which are the values used by the MIME email format. Unlike str_split(), which returns an array, chunk_split() returns one string.

The separator is added after the last chunk too, so the result always ends with the separator. This surprises people who use it to insert dashes or spaces into codes.

PHP
<?php
echo chunk_split("abcdefgh", 3, "-");
// abc-def-gh-

Try it

PHP Chunks and the trailing separator

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

PHP MIME-style lines and multibyte text

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Syntax

PHP
chunk_split(string $string, int $length = 76, string $separator = "\r\n"): string
Name Description
$string The text to split.
$length Number of bytes per chunk. Must be at least 1.
$separator The text inserted after each chunk.

Return value: the string with the separator after every chunk, including the last.

Errors: a ValueError if $length is less than 1.

Usage notes

  • Trailing separator. The output always ends with $separator. Trim it with rtrim(), or use implode($sep, str_split($s, $n)) to put separators only between chunks.
  • Bytes, not characters. A multibyte character can be cut in half. For UTF-8 text use mb_str_split() and join the pieces yourself.
  • Typical use. Wrapping base64 data to 76 characters per line for email or PEM files. base64_encode() plus chunk_split() is a classic pair; see base64_encode().
  • Short input. If the string is shorter than $length, you get the whole string plus the separator.
  • Empty string. An empty input returns just the separator.
  • Line breaks in text. For wrapping prose at word boundaries use wordwrap(); chunk_split() ignores word boundaries completely.