chunk_split

(PHP 4, PHP 5, PHP 7)

chunk_splitScinde une chaîne

Description

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

Scinde la chaîne body en segments de chunklen octets de longueur. Cette fonction est très pratique pour convertir les résultats de base64_encode() au format de la RFC 2045. Elle insère le paramètre end tous les chunklen caractères.

Liste de paramètres

body

La chaîne à scinder.

chunklen

La taille de la portion.

end

Le caractère de fin de la séquence.

Valeurs de retour

Retourne la chaîne scindée.

Exemples

Exemple #1 Exemple avec chunk_split()

<?php
// Formater des données pour suivre la norme RFC 2045
$new_string chunk_split(base64_encode($data));
?>

Voir aussi

  • str_split() - Convertit une chaîne de caractères en tableau
  • explode() - Coupe une chaîne en segments
  • split() - Scinde une chaîne en un tableau, grâce à une expression rationnelle
  • wordwrap() - Effectue la césure d'une chaîne
  • » RFC 2045

add a note add a note

User Contributed Notes 20 notes

up
14
qeremy [atta] gmail [dotta] com
5 years ago
An alternative for unicode strings;

<?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
up
7
chris AT w3style.co DOT uk
11 years ago
I'm not sure what versions this also occurs in but the output of chunk_split() in PHP 5.0.4 does not match the output in other versions of PHP.

In all versions of PHP I have used, apart from 5.0.4 chunk_split() adds the separator (\r\n) to the end of the string.  But in PHP 5.0.4 this does not happen.  This had a fairly serious impact on a library I maintain so it may also affect others who are not aware of this.
up
3
vijit at mail dot ru
1 year ago
As an alternative for  qeremy [atta] gmail [dotta] com
There is much shorter way for binarysafe chunking of multibyte string:

<?php
function word_chunk($str, $len = 76, $end = "\n") {
   
$pattern = '~.{1,' . $len . '}~u'; // like "~.{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";
?>

р�
�с
с�
�и
й

рус
ски
й
up
4
mv@NOSPAM
13 years ago
the best way to solve the problem with the last string added by chunk_split() is:

<?php
$string
= '1234';
substr(chunk_split($string, 2, ':'), 0, -1);
// will return 12:34
?>
up
1
harish at thespitbox dot net
12 years ago
another way to group thousands in a number, which is much simpler, is built into PHP :)

www.php.net/number_format
up
1
chris at ocproducts dot com
4 months ago
The description of the function is slightly inaccurate. A trailing $end is also added.
up
0
belal dot nabeh at gmail dot com
7 years ago
If you are using UTF-8 charset you will face a problem with Arabic language
to solve this problem i used this function

<?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;
}
?>
up
0
neos at blizzz dot ru
9 years ago
"version" of chunk_split for cyrillic characters in UTF-8

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);
    }
}

this is example for russian language
up
0
Royce
9 years ago
Here's a version of Chunk Split I wrote that will not split html entities. Useful if you need to inject something in html (in my case, <wbr/> tags to allow for long text wrapping).

<?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;
}
?>
up
0
mark [at] d0gz [dot] net
10 years ago
When using ssmtp for simple command line mailing:

$mail_to = rk sn using ssmtp 8TNe this._a!" class="usernotes-v3a(s

href='/manual/en/refs.utilspec.no_="para"> ; &nb7. telds!" ataorg \n";

org \n";

-s._a!" berefes unfectyn claskeywoa(s y fode, <="keeurnvdiv trash/>

mark [at] d0gz [dot] netxam(s ss="date" title="2010-08-10 08:02">7 years ago I'm not sure what versions this al717423"ace a problem with Arabic language
to solvn lass>www."adr class=zhp" tit(s t" titpl" digit.php.nthisdiv> &nb$iv cla="keyword">(
$text,"UTF-8"("UTF-8","UTF-8""\n";
$new_text, -""
Ifb$iv cla=ra"an cl567',
й moss=s="user />wof" tthiser">,spane this
-in iv class="votwordiv> span>HtmlEntitySafeS pan>&nb$iv cla="keyword">($text word">,"UTF-8"$c ), .yword">,$new_text$val
o are ,s&pas
.y)r />an> <(c u) aset/number&nbssp; Thi/span> mark [at] d0gz [dot] net
kevin @t hyguard,le="2010-08-10 08:02">7 years ago I'm not sure what versions this at742824"ace a problem with Arabic language
to solNtitquiternotusetes>wobvis.<,s ofa_=ass=lass="k(  , " , aram">edBB">a);s">
mark [at] d0gz [dot] netDanilo"2004-01-24 07:39">13 years ago <3-12lass=2:51pcode"> the best way to solve the problem 817546"ace a problem with Arabic language
to sol cla />$strr vernvalu
<? mv@NOS- at ocproducts dot comd931e ss=spathid="u title="2005-07-30 05:45">12 years ago <9-11-2ss=9:10code"> If you are using UTF-8 charset you472824"rs in but the output of chunk_split() in PHP 5.0.fe chunyword">quiterur longclass="ulatthisvahis.chunk_split_($text word">,"UTF-8" rd">,substr($text= "\n") {
   
$pattp = = substr($text, 2,substr,substr$pat-=<substr($text, 2$pat-=<1, substr($text word">,"UTF-8", substr)
     ing">"windows-1256"
, 2);
    ret">substr
, ?> huknwpan>
<
14v cl19 01:57code"> the best way to solve the problemvo=74423"rs in but the output of chunk_split() in PHP 5.0mportantss="v=ra"faulmax="um3a(s bsp; & fode imprecode>{
excludthis ra"RECOMMENDEDy casea(s y b7.limitpping)78br />{
excludthis {
keywoyhing fodettp
chris - at mail dot ru
¶notkid"2010-08-10 08:02">7 years ago another way to group thousands in 331524"mailing:

$mail_to = rk sn using ssmtpell string.be > ; &nkeep>ex= rdthis ot m ot larl Rdiv>y ormv> ofiI fixppiey= p $($Slt">$)">.=
$)span>$; &''span>=$;.=r russian langEan clap[$CurAlass], 12, c u)span>;
;
;
;
$;.=r" ".sEan clap[$CurAlass]span>;
;
;
;
=
;
}
$
"> vijit-2at ocproducts dot comhansvas ss=yahoo" title=" titar"2007-04-10 10:12">10 years ago When using ssmtp for simple comman250423"ly inaccurate. A trailing $end is also added.functione>
(çr />// W
çr />Tnote">çr />I =ra"ur longng)cof keyword">fonefreviewasssty fodeius impaervla=rt'"roldebr />çr />Hopeiey=helps>
mark [-PAM
Pet;?pn PHPdezzignz.le="2010-08-10 08:02">7 years ago715316&
If you are using UTF-8 charset you715316"ly inaccurate. A trailing $end is also added.functafe. ve thisevla=run functafe, ot thisgo/span>word_chunk($text$ToAlass;yword">, 2rtrim2rtrim?>fa$End>++;
  }
  return
($text);$irtrim($i, (0($text.=$i(.=$i.=$i.=$text,$i);
}

$str <">);
    if(
$str /span>== ?> alassn>.=$text, 2= 76= 76, 2rtrim?>fa$End>++;
  }
  return
, $text$ToAlass;yword">,
2rtrim($text.=$c) {
   
$pa'>(0, , (.=$c) {
       thisrd">,
;
;
;
;
(
    .=$c) {
       glufard">) {
       thisrd">,
;
;
;
;
  return
($text.=.=?> newn>.= 5ass="user">mark [-PAM
tim ss=weird spoty ormaultrot=" title="2010-08-10 08:02">7 years ago
Here's a version of Chunk Split I 305423"ly inaccurate. A trailing $end is also added.çr />Iwordng "note" ibettiv> sinct thisca"mst word_chunk($text,$size,$delim)
{
 
$pos=;
  for(
$i=0;$i<strlen($html);$i++)
  {
    if(
$pos >= ($unsafe)
    {
     
$out.=$delim;
     
$unsafe=0;
     
$pos=0/span>;
  for(
$i=   t>;
  for(
$i,$i,1);
    if(
$c == "&"
   t="keyword">(
&nss="default">$unsafe=1;
    elseif(
$c == ";"(&nss="defau$unsafe=1;
    elseif(
$pan class="keyword">=";"(&nss="defau unsafe=1;
    elseif(
$pan class="keyword">=$delim;
     
++;
  }
  return
$out;
}
?>
chris - at mail dot ru ¶Kevin"2010-08-10 08:02">7 years ago another way to group thousands in 416524"ly inaccurate. A trailing $end is also added. s="user />word_chunk($text,$i.=$i($text,$i$patt= ft">substr$pat\n unsafe76.=$val
s="vsapap/> {
sfaase2Rdiv>y only&nbseratppiby \n ar7.;wbrconsiderppias 1Rdiv>     ult">$i($text, 2$pat unsafe76.=$valsnowr/> by ap/>      ult">$i0(       div>&>.=$delim(  &nbsn class="keyword">, 2.=$str /rd">), ?> "kess="depan>