PHP Conference Japan 2024

chunk_split

(PHP 4、PHP 5、PHP 7、PHP 8)

chunk_split將字串分割成較小的區塊

說明

chunk_split(字串 $string, 整數 $length = 76, 字串 $separator = "\r\n"): 字串

可以用來將字串分割成較小的區塊,這對於例如將 base64_encode() 的輸出轉換以符合 RFC 2045 語義非常有用。它會在每 length 個字元後插入 separator

參數

string

要分割的字串。

length

區塊長度。

separator

行尾序列。

傳回值

傳回分割後的字串。

範例

範例 #1 chunk_split() 範例

<?php
// 使用 RFC 2045 語義格式化 $data
$new_string = chunk_split(base64_encode($data));
?>

參見

新增筆記

使用者貢獻的筆記 19 則筆記

22
vijit at mail dot ru
8 年前
作為 qeremy [atta] gmail [dotta] com 的替代方案
有一種更短的方法可以對多位元組字串進行二進制安全區塊分割

<?php
function word_chunk($str, $len = 76, $end = "\n") {
$pattern = '~.{1,' . $len . '}~u'; // 類似 "~.{1,76}~u"
$str = preg_replace($pattern, '$0' . $end, $str);
return
rtrim($str, $end);
}

$str = 'русский';
echo
chunk_split($str, 3) ."\n";
echo
word_chunk($str, 3) . "\n";
?>

р�
�с
с�
�и
й

рус
ски
й
24
qeremy [atta] gmail [dotta] com
12 年前
Unicode 字串的替代方案;

<?php
function chunk_split_unicode($str, $l = 76, $e = "\r\n") {
$tmp = array_chunk(
preg_split("//u", $str, -1, PREG_SPLIT_NO_EMPTY), $l);
$str = "";
foreach (
$tmp as $t) {
$str .= join("", $t) . $e;
}
return
$str;
}

$str = "Yarım kilo çay, yarım kilo şeker";
echo
chunk_split($str, 4) ."\n";
echo
chunk_split_unicode($str, 4);
?>

Yar�
�m k
ilo
çay
, ya
rım
kil
o ş
eker

Yarı
m ki
lo ç
ay,
yarı
m ki
lo ş
eker
11
chris AT w3style.co DOT uk
18 年前
我不確定這也發生在哪些版本中,但 PHP 5.0.4 中 chunk_split() 的輸出與其他 PHP 版本的輸出不符。

在我使用過的所有 PHP 版本中,除了 5.0.4 之外,chunk_split() 都會在字串的末尾新增分隔符號 (\r\n)。但在 PHP 5.0.4 中,這種情況並未發生。這對我維護的一個函式庫產生了相當嚴重的影響,因此它也可能會影響其他不知道這一點的人。
7
chris at ocproducts dot com
7 年前
該函式的描述略有不準確。也會新增尾隨的 $end。
10
mv@NOSPAM
20 年前
解決 chunk_split() 新增的最後一個字串問題的最佳方法是

<?php
$string
= '1234';
substr(chunk_split($string, 2, ':'), 0, -1);
// 將會回傳 12:34
?>
4
hansvane at yahoo dot com dot ar
17 年前
這個函式非常簡單,許多其他的函式在 PHP 5 甚至某些在 4 中也能做到,這個函式的好處是它可以在 PHP 3.0.6 和 4 上運作。

function split_hjms_chars($xstr, $xlenint, $xlaststr)
{
$texttoshow = chunk_split($xstr,$xlenint,"\r\n");
$texttoshow = split("\r\n",$texttoshow);
$texttoshow = $texttoshow[0].$xlaststr;
return $texttoshow;
}

// 使用範例

echo split_hjms_chars("This is your text",6,"...");

// 將會回傳

This i...

這對於在預覽列表中截斷長文本,以及當伺服器較舊時很有用。

希望對某些人有幫助。 Hans Svane
4
Anonymous
10 年前
重要的注意事項是最大行長度和建議的行長度。標準規定:
「訊息中的行必須最多為 998 個字元,不包括 CRLF,但建議將行限制為 78 個字元,不包括 CRLF。」

請參閱 PHP 手冊中的 chunk_split(),其預設設定為 76 個字元的區塊長度,並在行尾加上 "\r\n"。
5
neos at blizzz dot ru
16 年前
用於 UTF-8 中西里爾字母的 "chunk_split" "版本"

public function UTFChunk($Text,$Len = 10,$End = "\r\n")
{
if(mb_detect_encoding($Text) == "UTF-8")
{
return mb_convert_encoding(
chunk_split(
mb_convert_encoding($Text, "KOI8-R","UTF-8"), $Len,$End
),
"UTF-8", "KOI8-R"
);
} else
{
return chunk_split($Text,$Len,$End);
}
}

這是俄語的範例
4
Royce
16 年前
這是我寫的一個 Chunk Split 版本,它不會分割 HTML 實體。如果您需要在 HTML 中注入一些東西(在我的情況下,是 <wbr/> 標籤以允許長文本換行)這會很有用。

<?php
function HtmlEntitySafeSplit($html,$size,$delim)
{
$pos=0;
for(
$i=0;$i<strlen($html);$i++)
{
if(
$pos >= $size && !$unsafe)
{
$out.=$delim;
$unsafe=0;
$pos=0;
}
$c=substr($html,$i,1);
if(
$c == "&")
$unsafe=1;
elseif(
$c == ";")
$unsafe=0;
$out.=$c;
$pos++;
}
return
$out;
}
?>
4
xamine at gmail dot com
18 年前
回覆 "adrian at zhp dot inet dot pl" 的數字分組函式
<?php
$number
= strrev(chunk_split (strrev($number), 3,' '));
//如果 $number 是 '1234567',結果會是 '1 234 567'。
?>

使用內建的 number_format() 函式可以更簡單地實現此目的。

<?php
$number
= number_format($number,2,"."," ");

//這會將 $number 四捨五入到小數點後 2 位,使用點號 (".")
//作為小數點,空格 (" ") 作為千位分隔符。

?>
5
kevin @t hyguard,com
19 年前
雖然不是很明顯,但...

你可以透過以下方式 un_chunk_split()

$long_str = str_replace( "\r\n", "", $chunked_str );
3
harish at thespitbox dot net
19 年前
另一種將數字千位分組的方法,它更簡單,且內建於 PHP 中 :)

www.php.net/number_format
4
mark [at] d0gz [dot] net
17 年前
當使用 ssmtp 進行簡單的命令列郵件發送時

$mail_to = "destination@emailbox.com";
$msg = "這會是一個實際的 base64_encoded gzip 訊息";
$date = date(r);
$mail = "X-FROM: root@sender.org \n";
$mail .= "X-TO: ".$mail_to. " \n";
$mail .= "To: ".$mail_to. " \n";
$mail .= "Date: $date \n";
$mail .= "From: root@sender.org \n";
$mail .= "Subject: lifecheck \n";
$mail .= $msg." \n";
exec("echo '$mail' | /usr/sbin/ssmtp ".$mail_to);

請務必對您的訊息主體調用 chunk_split() - ssmtp 對於長行會不滿意,並隨後會損壞您的訊息。
4
dampee at earthlink dot net
15 年前
我發現這對於模擬各種紙牌洗牌方式很有用。這很幽默,但可以模擬多副牌的切牌和其他(不完全)隨機事件。

<?php
function truffle_shuffle($body, $chunklen = 76, $end = "\r\n")
{
$chunk = chunk_split($body, $chunklen, "-=blender=-");
$truffle = explode("-=blender=-",$chunk);
$shuffle = shuffle($truffle);
$huknc = implode($end,$shuffle);
return
$huknc;
}
?>
3
Danilo
20 年前
>> chunk_split 也會在最後一次出現後添加斷點。

這應該不是問題

substr(chunk_split('FF99FF', 2, ':'),0,8);
將會回傳 FF:99:FF
2
belal dot nabeh at gmail dot com
14 年前
如果您使用的是 UTF-8 字元集,您會遇到阿拉伯語的問題
為了解決這個問題,我使用了這個函式

<?php
function chunk_split_($text,$length,$string_end)
{
$text = iconv("UTF-8","windows-1256",$text);
$text = str_split($text);
foreach(
$text as $val)
{
if(
$a !== $val)
{
$a = $val;
$x = 0;
}else{
$a = $val;
$x++;
}
if(
$x > $length)
{
$new_text .= $val.$string_end;
$x = 0;
}else
{
$new_text .= $val;
}

}
$new_text = iconv("windows-1256","UTF-8",$new_text);
return
$new_text;
}
?>
-1
Kevin
19 年前
給 phpkid

這是一個更簡單的解決方案。

<?php
function longWordWrap($string) {
$string = str_replace("\n", "\n ", $string); // 在換行符號後新增一個空格,這樣僅由 \n 分隔的兩個單字不會被視為一個單字
$words = explode(" ", $string); // 現在以空格分隔
foreach ($words as $word) {
$outstring .= chunk_split($word, 12, " ") . " ";
}
return
$outstring;
}
?>
-3
tim at weird spots in my crotch dot com
16 年前
@Royce

我認為這個更好,因為你仍然可以在文字中使用 & 符號

<?php
function HtmlEntitySafeSplit($html,$size,$delim)
{
$pos=0;
for(
$i=0;$i<strlen($html);$i++)
{
if(
$pos >= $size && !$unsafe)
{
$out.=$delim;
$unsafe=0;
$pos=0;
}
$c=substr($html,$i,1);
if(
$c == "&")
$unsafe=1;
elseif(
$c == ";")
$unsafe=0;
elseif(
$c == " ")
$unsafe=0;
$out.=$c;
$pos++;
}
return
$out;
}
?>
-3
phpkid
19 年前
嗯,我寫的聊天室程式碼一直有問題,如果有很長的單字,它會不斷擴展 <TD>,但我用這個方法解決了

function PadString($String){
$Exploded = explode(" ", $String);
$Max_Parts = count($Exploded);

$CurArray = 0;
$OutString = '';
while($CurArray<=$Max_Parts)
{
$Peice_Size = strlen($Exploded[$CurArray]);
if($Peice_Size>15)
{
$OutString .= chunk_split($Exploded[$CurArray], 12, " ");
$CurArray++;
} else {
$OutString .= " ".$Exploded[$CurArray];
$CurArray++;
}
}

return $OutString;
}
To Top