Oihana PHP

chunk.php

Table of Contents

Functions

chunk()  : string
Splits a string into groups of length `$size`, separated by `$separator`.

Functions

chunk()

Splits a string into groups of length `$size`, separated by `$separator`.

chunk(string|null $source, int $size[, string $separator = ' ' ][, bool $utf8 = false ]) : string

This function supports both simple ASCII strings and full Unicode strings.

When $utf8 is true, the function uses grapheme-safe operations (grapheme_strlen / grapheme_substr) to correctly handle composed characters, accented letters, surrogate pairs, and emojis.

When $utf8 is false, a faster byte-based method is used (strlen / substr), which works well for ASCII.

Examples

ASCII examples:

chunk('565448', 2);          // "56 54 48"
chunk('1525', 2, '-');       // "15-25"
chunk('25', 2);              // "25"
chunk('123456789', 3, ':');  // "123:456:789"

Unicode / accents:

chunk('éàüö', 2, ' ', true); // "éà üö"

Emoji:

chunk('💛❤️💛', 2, ' ', true); // "💛 ❤️ 💛"

Null or empty source:

chunk(null, 2); // ""
chunk('', 3);   // ""
Parameters
$source : string|null

The source string to split. If null, it is treated as an empty string.

$size : int

The length of each group. Must be greater than 0.

$separator : string = ' '

The separator string to insert between groups. Default is a single space.

$utf8 : bool = false

Whether to use Unicode-aware grapheme-safe splitting. Default is false.

Tags
throws
InvalidArgumentException

Thrown if $size is less than or equal to 0.

author

Marc Alcaraz (ekameleon)

since
1.0.8
Return values
string

The resulting string after grouping.


        
On this page

Search results