chunk_split()

1. 定义

该函数将指定字符串按长度分割成小块,并可指定每小块的结尾内容。 返回被切割后的字符串。

2. 语法

chunk_split ( string $string [, int $chunklen = 76 [, string $end = "\r\n" ]] ) : string

3. 参数说明

参数 可选性 数据类型 描述
$string 必需 字符串 待切割的字符串
$chunklen 可选 整型 每个切块的长度
$end 可选 字符串 每个切块末尾的内容

4. 示例

<?php

// chunk_split()
// 将指定字符串按长度分割成小块,并可指定每小块的结尾内容

$str = 'I love php';
$res = chunk_split($str, 2, '__');
var_dump($res);// 输出:string(20) "I __lo__ve__ p__hp__"

$str = file_get_contents('https://loripsum.net/api/20/short/headers');

// 限定每行最多80个字符
$res = chunk_split($str, 80, "\n");

if(!file_exists('../tmp')) {
    @mkdir('../tmp', 0777, true);
}
file_put_contents('../tmp/tmp.txt', $res);

5. 延展阅读

  • str_split():将字符串分割成定长的子字符串,然后将其存入数组
  • explode():使用一个字符串分割另一个字符串,返回被分割后子字符串组成的数组
  • wordwrap():使用特定字符串将指定字符串打断为指定宽度的子字符串