chunk_split

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

按固定长度分块并在每块后插入分隔符(默认 \r\n)——为 MIME(RFC 2045)把 base64 按行折断而生,各语言无直接对应,普遍手写循环。

C C23

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

/* PHP chunk_split 的微缩实现:每 len 个字符后插入 sep */
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;
}
输出
ABCD|EFGH|IJKL|MNOP|
ABC-DEF-GH-

C++ C++26

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

// PHP chunk_split 的微缩实现:每 len 个字符后插入 sep
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;
}
输出
ABCD|EFGH|IJKL|MNOP|
ABC-DEF-GH-

C# v11.0.100

v11.0.100
// PHP chunk_split 的微缩实现:每 len 个字符后插入 sep
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, "-"));
输出
ABCD|EFGH|IJKL|MNOP|
ABC-DEF-GH-

Go v1.27.4

v1.27.4
package main

import "fmt"

// PHP chunk_split 的微缩实现:每 len 个字符后插入 sep
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, "-"))
}
输出
ABCD|EFGH|IJKL|MNOP|
ABC-DEF-GH-

Java v27.0.1

v27.0.1
public class Main {
    // PHP chunk_split 的微缩实现:每 len 个字符后插入 sep
    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, "-"));
    }
}
输出
ABCD|EFGH|IJKL|MNOP|
ABC-DEF-GH-

JavaScript v26.13.1

v26.13.1
// PHP chunk_split 的微缩实现:每 len 个字符后插入 sep
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, "-"));
输出
ABCD|EFGH|IJKL|MNOP|
ABC-DEF-GH-

PHP v8.6.0

v8.6.0
// 每 4 个字符分一块并插入分隔符(含尾部那个)
echo chunk_split("ABCDEFGHIJKLMNOP", 4, "|"), "\n";
echo chunk_split("ABCDEFGH", 3, "-"), "\n";
// 经典用途:为 MIME(RFC 2045)把 base64 载荷按 60 字符折行
$b64 = base64_encode(str_repeat("PHP", 30)); // 120 字符 → 折成 2 行
// 每行 60 字符 + \r\n,所以总长 2 * 62 = 124
echo strlen(chunk_split($b64, 60)), "\n";
输出
ABCD|EFGH|IJKL|MNOP|
ABC-DEF-GH-
124

Python v3.15.2

v3.15.2
# PHP chunk_split 的微缩实现:每 len 个字符后插入 sep
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 只切不插尾分隔符(语义不同)
import textwrap
print(textwrap.wrap("ABCDEFGH", 3))
输出
ABCD|EFGH|IJKL|MNOP|
ABC-DEF-GH-
['ABC', 'DEF', 'GH']

Rust v1.99.1

v1.99.1
// PHP chunk_split 的微缩实现:每 len 个字符后插入 sep
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, "-"));
}
输出
ABCD|EFGH|IJKL|MNOP|
ABC-DEF-GH-

TypeScript v26.13.1

v26.13.1
// PHP chunk_split 的微缩实现:每 len 个字符后插入 sep
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, "-"));
输出
ABCD|EFGH|IJKL|MNOP|
ABC-DEF-GH-

语言差异说明

C:手写分块循环(示例);产出可直接喂给需要按行折断的 MIME 构造器。

C++:substr 逐块拼接(示例);无标准库对应,手写是常态。

C#:StringBuilder + Substring 循环(示例);无内建对应。

Go:切片逐块拼接(示例);strings.Split 是反向操作且不带分隔符回插。

Java:StringBuilder 循环(示例);Guava 的 Splitter.fixedLength 只切不插。

JavaScript:slice 循环(示例);正则 s.replace(RegExp(".{1,4}", "g"), "$&|") 亦可但难读。

PHP:第三个参数默认 "\r\n"、第二参默认 76——正是 RFC 2045 的 base64 折行参数;末块不满也照样插分隔符(含尾部);与 wordwrap 的区别:chunk_split 是硬切(不看词边界),wordwrap 会尽量保词完整。

Python:手写推导式(示例);textwrap.wrap 只切不插分隔符(列表语义),语义不同需转换。

Rust:手写循环按字节切(示例);示例串为纯 ASCII 所以字节切安全,多字节字符须用 char_indices。

TypeScript:同 JavaScript 的 slice 循环(示例)。