chunk_split

chunk_split(string $string, int $length = 76, string $separator = "\r\n"): string

Splits a string into fixed-length chunks with a separator inserted after each (default \r\n) — built for folding base64 into lines for MIME (RFC 2045); most languages have no direct counterpart and hand-write the loop.

C C23

C23
#include <stdio.h>
#include <string.h>

/* PHP chunk_split in miniature: insert sep after every len chars */
static void chunk_split(const char *s, size_t len, const char *sep, char *out) {
    size_t k = 0, n = strlen(s);
    for (size_t i = 0; i < n; i += len) {
        for (size_t j = i; j < i + len && j < n; j++)
            out[k++] = s[j];
        for (const char *p = sep; *p; p++)
            out[k++] = *p;
    }
    out[k] = '\0';
}

int main(void) {
    char buf[64] = {0};
    chunk_split("ABCDEFGHIJKLMNOP", 4, "|", buf);
    printf("%s\n", buf);
    chunk_split("ABCDEFGH", 3, "-", buf);
    printf("%s\n", buf);
    return 0;
}
Output
ABCD|EFGH|IJKL|MNOP|
ABC-DEF-GH-

C++ C++26

C++26
#include <iostream>
#include <string>

// PHP chunk_split in miniature: insert sep after every len chars
static std::string chunk_split(const std::string &s, size_t len, const std::string &sep) {
    std::string out;
    for (size_t i = 0; i < s.size(); i += len) {
        out += s.substr(i, len);
        out += sep;
    }
    return out;
}

int main() {
    std::cout << chunk_split("ABCDEFGHIJKLMNOP", 4, "|") << "\n";
    std::cout << chunk_split("ABCDEFGH", 3, "-") << "\n";
    return 0;
}
Output
ABCD|EFGH|IJKL|MNOP|
ABC-DEF-GH-

C# v11.0.100

v11.0.100
// PHP chunk_split in miniature: insert sep after every len chars
static string ChunkSplit(string s, int len, string sep) {
    var b = new System.Text.StringBuilder();
    for (int i = 0; i < s.Length; i += len) {
        b.Append(s.Substring(i, Math.Min(len, s.Length - i)));
        b.Append(sep);
    }
    return b.ToString();
}
Console.WriteLine(ChunkSplit("ABCDEFGHIJKLMNOP", 4, "|"));
Console.WriteLine(ChunkSplit("ABCDEFGH", 3, "-"));
Output
ABCD|EFGH|IJKL|MNOP|
ABC-DEF-GH-

Go v1.27.4

v1.27.4
package main

import "fmt"

// PHP chunk_split in miniature: insert sep after every len chars
func chunkSplit(s string, length int, sep string) string {
	out := ""
	for i := 0; i < len(s); i += length {
		end := i + length
		if end > len(s) {
			end = len(s)
		}
		out += s[i:end] + sep
	}
	return out
}

func main() {
	fmt.Println(chunkSplit("ABCDEFGHIJKLMNOP", 4, "|"))
	fmt.Println(chunkSplit("ABCDEFGH", 3, "-"))
}
Output
ABCD|EFGH|IJKL|MNOP|
ABC-DEF-GH-

Java v27.0.1

v27.0.1
public class Main {
    // PHP chunk_split in miniature: insert sep after every len chars
    static String chunkSplit(String s, int len, String sep) {
        StringBuilder b = new StringBuilder();
        for (int i = 0; i < s.length(); i += len) {
            b.append(s, i, Math.min(i + len, s.length()));
            b.append(sep);
        }
        return b.toString();
    }

    public static void main(String[] args) {
        System.out.println(chunkSplit("ABCDEFGHIJKLMNOP", 4, "|"));
        System.out.println(chunkSplit("ABCDEFGH", 3, "-"));
    }
}
Output
ABCD|EFGH|IJKL|MNOP|
ABC-DEF-GH-

JavaScript v26.13.1

v26.13.1
// PHP chunk_split in miniature: insert sep after every len chars
function chunkSplit(s, len, sep) {
  let out = "";
  for (let i = 0; i < s.length; i += len) out += s.slice(i, i + len) + sep;
  return out;
}
console.log(chunkSplit("ABCDEFGHIJKLMNOP", 4, "|"));
console.log(chunkSplit("ABCDEFGH", 3, "-"));
Output
ABCD|EFGH|IJKL|MNOP|
ABC-DEF-GH-

PHP v8.6.0

v8.6.0
// split every 4 chars and insert a separator (trailing separator included)
echo chunk_split("ABCDEFGHIJKLMNOP", 4, "|"), "\n";
echo chunk_split("ABCDEFGH", 3, "-"), "\n";
// classic use: fold a base64 payload at 60 chars for MIME (RFC 2045)
$b64 = base64_encode(str_repeat("PHP", 30)); // 120 chars -> 2 folded lines
// each line is 60 chars + \r\n, so the total is 2 * 62 = 124
echo strlen(chunk_split($b64, 60)), "\n";
Output
ABCD|EFGH|IJKL|MNOP|
ABC-DEF-GH-
124

Python v3.15.2

v3.15.2
# PHP chunk_split in miniature: insert sep after every len chars
def chunk_split(s: str, length: int, sep: str) -> str:
    return "".join(s[i:i + length] + sep for i in range(0, len(s), length))

print(chunk_split("ABCDEFGHIJKLMNOP", 4, "|"))
print(chunk_split("ABCDEFGH", 3, "-"))
# textwrap.wrap splits without the trailing separator (different semantics)
import textwrap
print(textwrap.wrap("ABCDEFGH", 3))
Output
ABCD|EFGH|IJKL|MNOP|
ABC-DEF-GH-
['ABC', 'DEF', 'GH']

Rust v1.99.1

v1.99.1
// PHP chunk_split in miniature: insert sep after every len chars
fn chunk_split(s: &str, len: usize, sep: &str) -> String {
    let bytes = s.as_bytes();
    let mut out = String::new();
    let mut i = 0usize;
    while i < bytes.len() {
        let end = (i + len).min(bytes.len());
        out.push_str(&s[i..end]);
        out.push_str(sep);
        i += len;
    }
    out
}

fn main() {
    println!("{}", chunk_split("ABCDEFGHIJKLMNOP", 4, "|"));
    println!("{}", chunk_split("ABCDEFGH", 3, "-"));
}
Output
ABCD|EFGH|IJKL|MNOP|
ABC-DEF-GH-

TypeScript v26.13.1

v26.13.1
// PHP chunk_split in miniature: insert sep after every len chars
function chunkSplit(s: string, len: number, sep: string): string {
  let out = "";
  for (let i = 0; i < s.length; i += len) out += s.slice(i, i + len) + sep;
  return out;
}
console.log(chunkSplit("ABCDEFGHIJKLMNOP", 4, "|"));
console.log(chunkSplit("ABCDEFGH", 3, "-"));
Output
ABCD|EFGH|IJKL|MNOP|
ABC-DEF-GH-

Language differences

C: hand-written chunking loop (example); the output can feed any MIME builder that needs folded lines.

C++: substr concatenation per chunk (example); no standard library counterpart, hand-writing is the norm.

C#: StringBuilder with a Substring loop (example); no built-in counterpart.

Go: slice concatenation per chunk (example); strings.Split is the reverse operation and does not re-insert separators.

Java: StringBuilder loop (example); Guava's Splitter.fixedLength splits without inserting.

JavaScript: slice loop (example); the regex s.replace(RegExp(".{1,4}", "g"), "$&|") also works but is hard to read.

PHP: the third parameter defaults to "\r\n" and the second to 76 — exactly the RFC 2045 base64 folding parameters; a short final chunk still gets the separator (trailing one included); versus wordwrap: chunk_split is a hard cut (word boundaries ignored) while wordwrap tries to keep words intact.

Python: hand-written comprehension (example); textwrap.wrap splits without a trailing separator (list semantics) — a different contract that needs conversion.

Rust: hand-written loop slicing by bytes (example); the sample strings are pure ASCII so byte slicing is safe, multi-byte characters need char_indices.

TypeScript: same slice loop as JavaScript (example).