PHP - chunk_split() 函式



PHP 的 chunk_split() 函式用於將字串拆分為一系列指定長度的較小塊。 “塊”指的是字串的較小部分,可以包含單個字元、雙字元或多個字元。

此函式接受一個名為“separator”的引數,該引數在每個指定長度的字元後插入。

語法

以下是 PHP chunk_split() 函式的語法:

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

引數

以下是此函式的引數:

  • str - 要分塊的字串。
  • length - 每個塊的長度。預設長度為 76。
  • sepa - 用於分隔塊的字串,可以是換行符序列或任何其他字串。

返回值

此函式返回分塊後的字串。

示例 1

以下是 PHP chunk_split() 函式的基本示例:

<?php
   $str = "Tutorialspoint";
   echo "The string to be chunked: $str";
   $length = 1;
   $separator = ".";
   echo "\nThe chunk length: $length";
   echo "\nSeparator: $separator";
   echo "\nThe chunked string: ".chunk_split($str,$length,$separator);
?>

輸出

以上程式產生以下輸出:

The string to be chunked: Tutorialspoint
The chunk length: 1
Separator: .
The chunked string: T.u.t.o.r.i.a.l.s.p.o.i.n.t.

示例 2

如果塊長度大於 0,則字串將被拆分為指定長度的較小塊。

以下是 PHP chunk_split() 函式的另一個示例。我們使用此函式將此字串“Chunked String”拆分為指定長度 2 的較小塊:

<?php
   $str = "Chunked String";
   echo "The string to be chunked: $str";
   $length = 2;
   $separator = "/";
   echo "\nThe chunk length: $length";
   echo "\nSeparator: $separator";
   echo "\nThe chunked string: ".chunk_split($str,$length,$separator);
?>

輸出

執行以上程式後,將顯示以下輸出:

The string to be chunked: Chunked String
The chunk length: 2
Separator: /
The chunked string: Ch/un/ke/d /St/ri/ng/

示例 3

如果省略“separator”引數,則 PHP chunk_split() 函式會將字串拆分為較小的塊,並使用預設值“\n”分隔它們:

<?php
   $str = "Hello World";
   echo "The string to be chunked: $str";
   $length = 1;
   #$separator = "@tp";
   echo "\nThe chunk length: $length";
   #echo "\nSeparator: $separator";
   echo "\nThe chunked string: ".chunk_split($str,$length);
?>

輸出

以下是以上程式的輸出:

The string to be chunked: Hello World
The chunk length: 1
The chunked string: H
e
l
l
o

W
o
r
l
d
php_function_reference.htm
廣告