字符串函数
在线手册:中文 英文
PHP手册

str_split

(PHP 5)

str_split将字符串转换为数组

说明

array str_split ( string $string [, int $split_length = 1 ] )

将一个字符串转换为数组。

参数

string

输入字符串。

split_length

每一段的长度。

返回值

如果指定了可选的 split_length 参数,返回数组中的每个元素均为一个长度为 split_length 的字符块,否则每个字符块为单个字符。

如果 split_length 小于 1,返回 FALSE。如果 split_length 参数超过了 string 超过了字符串 string 的长度,整个字符串将作为数组仅有的一个元素返回。

范例

Example #1 str_split() 使用范例

<?php

$str 
"Hello Friend";

$arr1 str_split($str);
$arr2 str_split($str3);

print_r($arr1);
print_r($arr2);

?>

以上例程会输出:

Array
(
    [0] => H
    [1] => e
    [2] => l
    [3] => l
    [4] => o
    [5] =>
    [6] => F
    [7] => r
    [8] => i
    [9] => e
    [10] => n
    [11] => d
)

Array
(
    [0] => Hel
    [1] => lo
    [2] => Fri
    [3] => end
)

参见


字符串函数
在线手册:中文 英文
PHP手册
PHP手册 - N: 将字符串转换为数组

用户评论:

Erick Carvalho (14-Mar-2012 03:26)

For php4 ;D
<?php
function str_split($string, $length = 1)
{
   
$return = array();
   
$count = 0;
       
    for(
$i = 0; $i < strlen($string); $i++)
    {
        if(
$i % $length == 0)
        {
           
$count++;
            continue;
        }
           
       
$return[$count] .= $string{$i};
    }
       
    return
$return;
}
?>

qeremy [atta] gmail [dotta] com (24-Feb-2012 08:23)

A proper unicode string split;

<?php
function str_split_unicode($str, $l = 0) {
    if (
$l > 0) {
       
$ret = array();
       
$len = mb_strlen($str, "UTF-8");
        for (
$i = 0; $i < $len; $i += $l) {
           
$ret[] = mb_substr($str, $i, $l, "UTF-8");
        }
        return
$ret;
    }
    return
preg_split("//u", $str, -1, PREG_SPLIT_NO_EMPTY);
}
?>

$s = "Il?k süt"; // Mild milk

print_r(str_split($s, 3));
print_r(str_split_unicode($s, 3));

Array
(
    [0] => Il?
    [1] => ?k
    [2] => sü
    [3] => t
)

Array
(
    [0] => Il?
    [1] => k s
    [2] => üt
)

anon (15-Jun-2010 04:53)

I needed a function that could split a string from the end with any left over chunk being at the beginning of the array (the beginning of the string).

<?php
function str_rsplit($str, $sz)
{
   
// splits a string "starting" at the end, so any left over (small chunk) is at the beginning of the array.   
   
if ( !$sz ) { return false; }
    if (
$sz > 0 ) { return str_split($str,$sz); }    // normal split
   
   
$l = strlen($str);
   
$sz = min(-$sz,$l);
   
$mod = $l % $sz;
   
    if ( !
$mod ) { return str_split($str,$sz); }    // even/max-length split

    // split
   
return array_merge(array(substr($str,0,$mod)), str_split(substr($str,$mod),$sz));
}

$str = 'aAbBcCdDeEfFg';
str_split($str,5); // return: {'aAbBc','CdDeE','fFg'}
str_rsplit($str,5); // return: {'aAbBc','CdDeE','fFg'}
str_rsplit($str,-5); // return: {'aAb','BcCdD','eEfFg'}

?>

seebz.net (03-May-2010 02:27)

here an equivalent function for unicode string :

<?php
function uni_strsplit($string, $split_length=1)
{
   
preg_match_all('`.`u', $string, $arr);
   
$arr = array_chunk($arr[0], $split_length);
   
$arr = array_map('implode', $arr);
    return
$arr;
}

nemostein at hotmail dot com (28-Aug-2009 07:51)

The manual don't says what is returned when you parse a different type of variable.

This is the example:

<?php

$str1
= "Long"; // More than 1 char
$str2 = "x"; // Only 1 char
$str3 = ""; // Empty String
$str4 = 34; // Integer
$str5 = 3.4; // Float
$str6 = true; // Bool
$str7 = null; // Null

$spl1 = str_split($str1);
$spl2 = str_split($str2);
$spl3 = str_split($str3);
$spl4 = str_split($str4);
$spl5 = str_split($str5);
$spl6 = str_split($str6);
$spl7 = str_split($str7);

echo
count($spl1); // 4
echo count($spl2); // 1
echo count($spl3); // 1
echo count($spl4); // 2
echo count($spl5); // 3
echo count($spl6); // 1
echo count($spl7); // 1

print_r($spl1);
print_r($spl2);
print_r($spl3);
print_r($spl4);
print_r($spl5);
print_r($spl6);
print_r($spl7);

/*

Array
(
    [0] => L
    [1] => o
    [2] => n
    [3] => g
)
Array
(
    [0] => x
)
Array
(
    [0] =>
)
Array
(
    [0] => 3
    [1] => 4
)
Array
(
    [0] => 3
    [1] => .
    [2] => 4
)
Array
(
    [0] => 1
)
Array
(
    [0] =>
)

*/

?>

mattias at lsahlin dot se (19-Mar-2009 02:46)

For those it may concern:

We encountered trubble when trying to str_split a UTF-8 encoded string, containing such Swedish letters as ?, ? and ?.

It seems that this function splits according to byte-length and not character length. So if the letter "?" takes 2 bytes, then str_split() will only return the first bite of the character "?".

We ain't 100% sure that this is the case but this was anyhow the result we got. So we used the multi-byte functions instead.

thax (24-Nov-2008 02:44)

Regarding ricordatis comment on preg_match_all('/./u',...) instead of preg_split('//u',...):
You'll have to use the pattern '/./us' with preg_match_all to get exactly the same behaviour w.r.t. newlines. Don't know if this is still faster, though. Oh, and the expected result is in $array[0].

rrelmy (04-Aug-2008 03:20)

revised function from tatsudoshi

Fixed some bugs, more php5 style compliant
<?php
if(!function_exists('str_split')) {
    function
str_split($string,$string_length=1) {
        if(
strlen($string)>$string_length || !$string_length) {
            do {
               
$c = strlen($string);
               
$parts[] = substr($string,0,$string_length);
               
$string = substr($string,$string_length);
            } while(
$string !== false);
        } else {
           
$parts = array($string);
        }
        return
$parts;
    }
}
?>

ricordati at web dot de (01-Aug-2008 03:21)

To split unicode text, preg_match_all('/./u', $text, $array); seems faster for large strings than the use of preg_split('//u', $text); suggested by "edgaras dot janusauskas at gmail dot com" below.

vec [ at t] g dot com (21-Jun-2008 04:38)

the fastast way (that fits my needs) to replace str_split() in php 4 i found is this:

<?php
if(!function_exists('str_split')) {
  function
str_split($string, $split_length = 1) {
   
$array = explode("\r\n", chunk_split($string, $split_length));
   
array_pop($array);
    return
$array;
  }
}
?>

i also tested the provided functions in the comments..

(the differences are 0.001 to 0.00001 sec)

saeedco (21-May-2008 11:20)

This function supportes utf8

(improvement of function str_split_php4)

i tried this function successfully with these languages
1- Chinese
2- Japanese
3- Arabic
4- Turkish
5- Urdu
6- Russian
7- Persian

<?php
function str_split_php4_utf8($str) {
   
// place each character of the string into and array
   
$split=1;
   
$array = array();
    for (
$i=0; $i < strlen( $str ); ){
       
$value = ord($str[$i]);
        if(
$value > 127){
            if(
$value >= 192 && $value <= 223)
               
$split=2;
            elseif(
$value >= 224 && $value <= 239)
               
$split=3;
            elseif(
$value >= 240 && $value <= 247)
               
$split=4;
        }else{
           
$split=1;
        }
           
$key = NULL;
        for (
$j = 0; $j < $split; $j++, $i++ ) {
           
$key .= $str[$i];
        }
       
array_push( $array, $key );
    }
    return
$array;
}
?>

lskatz at gmail dot com (07-May-2008 07:42)

A good use of str_split is reverse translating an amino acid sequence.

<?php
/* reverse translate an aa sequence using its dna counterpart */
function reverseTranslate($aaSeq,$ntSeq){
 
$nt=str_split($ntSeq,3);
 
$aa=str_split($aaSeq,1);
 
$gapChar=array('*','-');

 
$numAa=count($aa);
 
$ntIndex=0;
 
$newNtSeq="";
  for(
$i=0;$i<$numAa;$i++){
   
// if the aa is a gap, then just put on a gap character
   
if(in_array($aa[$i],$gapChar)){
     
$newNtSeq.='---';
    }
    else{
     
$newNtSeq.=$nt[$ntIndex];
     
$ntIndex++;
    }
  }
  return
$newNtSeq;
}
?>

kevin at metalaxe dot com (15-Mar-2008 04:49)

Response to "Richard Ayotte 18-Jan-2008 09:27":

Slight tweak to prevent the need to call another preg_replace, there were also some bugs in this that I'm surprised didn't get noticed (causing duplicate replaces between the preg_replace calls) :)

Please feel free to optimize further. I'm not the best with lookahead/behinds yet. I also removed the :upper/lower: and it seemed to speed things up too.

<?php
$test
= 'CustomerIDWithSomeOtherJETWords';

preg_replace('/(?!^)[A-Z]{2,}(?=[A-Z][a-z])|[A-Z][a-z]/', ' $0', $test));
?>

Shaves off a little time anyway. :)

Ap.Muthu (07-Feb-2008 12:20)

Syntax corrected version:-

<?php
   
if(! function_exists('str_split'))
    {
        function
str_split($text, $split = 1)
        {
           
$array = array();
           
            for (
$i = 0; $i < strlen($text); $i += $split)
            {
               
$array[] = substr($text, $i, $split);
            }
           
            return
$array;
        }
    }
?>

Richard Ayotte (18-Jan-2008 02:27)

Slight mod to the CamelCaseFormat regex that behaves better with strings with multiple upper case letters immediately following each other.

CustomerID -> Customer ID and not Customer I D

<?php
$test
= 'CustomerIDWithSomeOtherJETWords';

preg_replace('/(?!^)[[:upper:]][[:lower:]]/', ' $0', preg_replace('/(?!^)[[:upper:]]+/', ' $0', $test));
?>

Customer ID With Some Other JET Words

Anonymous (03-Jan-2008 08:04)

Version of str_split by rlpvandenberg at hotmail dot com is god-damn inefficient and when $i+$j > strlen($text) [last part of string] throws a lot of notice errors. This should work better:

    if(! function_exists('str_split'))
    {
        function str_split($text, $split = 1)
        {
            $array = array();
           
            for ($i = 0; $i < strlen($text);)
            {
                $array[] = substr($text, $i, $split);
                $i += $split;
            }
           
            return $array;
        }
    }

rlpvandenberg at hotmail dot com (19-Dec-2007 07:22)

The previous suggestion is almost correct (and will only working for strlen=1. The working PHP4 function is:

<code>
function str_split($text, $split = 1){
    //place each character of the string into and array
    $array = array();
    for ($i=0; $i < strlen($text); $i++){
        $key = "";
        for ($j = 0; $j < $split; $j++){
            $key .= $text[$i+$j]; 
        }
        $i = $i + $j - 1;
        array_push($array, $key);
    }
    return $array;
}
</code>

skore at skore dot de (30-Nov-2007 05:16)

dacmeaux at gmail dot com's version might work well for a $split value of 1, but above that, it just repeats the one character per array field and based on the $split value. The following does it right:

<?php
function str_split_php4( $text, $split = 1 ) {
   
// place each character of the string into and array
   
$array = array();
    for (
$i=0; $i < strlen( $text ); ){
       
$key = NULL;
        for (
$j = 0; $j < $split; $j++, $i++ ) {
           
$key .= $text[$i];
        }
       
array_push( $array, $key );
    }
    return
$array;
}
?>

mohd at ba7rain dot net (29-Nov-2007 10:24)

this function can perform a reverse str_split. I write it for PHP4 but you can rename It for other versions..

if ( !function_exists('str_split') ) {
function str_split($string,$split_length=1){
    $sign = (($split_length<0)?-1:1);
    $strlen = strlen($string);
    $split_length = abs($split_length);
    if ( ($split_length==0) || ($strlen==0) ){
            $result = false;
            //$result[] = "";
    }
    elseif ($split_length >= $strlen){
        $result[] = $string;
    }
    else {
        $length = $split_length;
        for ($i=0; $i<$strlen; $i++){
            $i=(($sign<0)?$i+$length:$i);
            $result[] = substr($string,$sign*$i,$length);
            $i--;
            $i=(($sign<0)?$i:$i+$length);
            if ( ($i+$split_length) > ($strlen) ){
                $length = $strlen-($i+1);
            }
            else {
                $length = $split_length;
            }
        }
    }
    return $result;
}
}

www dot wesley at gmail dot com (26-Nov-2007 12:12)

in response to Sam's CamelCase function:

<?php
$test
= 'CamelCaseFormat';

echo
preg_replace('/(?!^)[[:upper:]]/',' \0',$test);
?>

atolia at gmail----- dot com (10-Nov-2007 09:48)

i use this in PHP4

function str_split($str){
   return preg_split('//',$str);
}

magisano at cs dot unibo dot it (06-Nov-2007 04:14)

Even shorter version:

//place each character (or group of) of the
string into and array

function str_split_php4($sText, $iSplit = 1)
{
    $iSplit=(integer) $iSplit;       // sanity check
    if ($iSplit < 1) {  return false; }
    $aResult = array();
    for($i=0, $limit=strlen($sText); $i < $limit; $i+=$iSplit) {
        $aResult[]=substr($sText, $i, $iSplit);
    }
    return $aResult;
}

dacmeaux at gmail dot com (01-Nov-2007 09:57)

I was looking for a function that would split a string into an array like str_split() and found Razor's function above. Just though that I would simplify the code a little.

<?php
function str_split_php4($text, $split = 1){
   
//place each character of the string into and array
   
$array = array();
    for(
$i=0; $i < strlen($text); $i++){
       
$key = NULL;
        for (
$j = 0; $j < $split; $j++){
           
$key .= $text[$i]; 
        }
       
array_push($array, $key);
    }
    return
$array;
}
?>

Both mine and worksRazor's work well, I just prefer to use less code. I could have written one myself, but I was just being lazy.

Sam (25-Sep-2007 09:24)

A good way to use this method to convert CamelCase text into nice text would be-

<?php
       
/**
         Returns a formatted string based on camel case.
         e.g. "CamelCase" -> "Camel Case".
        */
       
function FormatCamelCase( $string ) {
               
$output = "";
                foreach(
str_split( $string ) as $char ) {
                       
strtoupper( $char ) == $char and $output and $output .= " ";
                       
$output .= $char;
                }
                return
$output;
        }
?>

edgaras dot janusauskas at gmail dot com (22-Aug-2007 01:30)

To split unicode text, use preg_split('//u', $text);

kjensen at iaff106 dot com (11-Aug-2007 08:59)

Here is what I use. I started with examples here but modified to my own version:

<?php
if (phpversion () < "5"){ // define PHP5 functions if server uses PHP4

function str_split($text, $split = 1)
{
if (!
is_string($text)) return false;
if (!
is_numeric($split) && $split < 1) return false;
$len = strlen($text);
$array = array();
$s = 0;
$e=$split;
while (
$s <$len)
    {
       
$e=($e <$len)?$e:$len;
       
$array[] = substr($text, $s,$e);
       
$s = $s+$e;
    }
return
$array;
}
}
?>

l0c4lh0st DOT nl AT gmail DOT com (12-Jun-2007 01:28)

how I can conwert
$string
 '1, 2, 5, 6, 10, 13, 23'
from ENUM at mySQL to

$array
[0] -> false
[1] -> true
[2] -> true
[3] -> false
[4] -> false
[5] -> true
[6] -> true
[7] -> false
[8] -> false
[9] -> false
[10] -> true
[11] -> false
[12] -> false
[13] -> true
[14] -> false
[15] -> false
...
[23] -> true

<?php
function enum_to_array($psEnum)
{
   
$aReturn = array();
   
$aTemp = explode(', ', $psEnum);
    for (
$i = $aTemp[0]; $i <= $aTemp[count($aTemp)-1]; $i++)
    {
       
$aReturn[$i] = in_array($i, $aTemp);
    }
}
?>

dhayes (07-Jun-2007 08:17)

@razor: this'll work for php4
<?php
$str
= 'two words';
$array = explode("\r\n", chunk_split($str,1));
?>

Razor (10-May-2007 08:02)

heres my version for php4 and below

<?php

function str_split_php4($text, $split = 1)
{
    if (!
is_string($text)) return false;
    if (!
is_numeric($split) && $split < 1) return false;
   
   
$len = strlen($text);
   
   
$array = array();
   
   
$i = 0;
   
    while (
$i < $len)
    {
       
$key = NULL;
       
        for (
$j = 0; $j < $split; $j += 1)
        {
           
$key .= $text{$i};
           
           
$i += 1;   
        }
       
       
$array[] = $key;
    }
   
    return
$array;
}

?>

(26-Feb-2007 04:32)

Problem with the post below me is, that the string can not contain the splitter "-1-".

Btw, here's my version.
<?php
function strsplit($str, $l=1) {
    do {
$ret[]=substr($str,0,$l); $str=substr($str,$l); }
    while(
$str != "");
    return
$ret;
}
?>

webmaster at nsssa dot ca (28-Oct-2006 03:45)

I noticed in the post below me that his function would return an array with an empty key at the end.

So here is just a little fix for it.

<?php

//Create a string split function for pre PHP5 versions
function str_split($str, $nr) {  
            
    
//Return an array with 1 less item then the one we have
    
return array_slice(split("-l-", chunk_split($str, $nr, '-l-')), 0, -1);
     
}

?>

(05-Oct-2006 01:14)

//fast & short version od str_split PHP3, 4x
function string_split($str, $nr){    
    return split("-l-", chunk_split($str, $nr, '-l-'));
}
//example :
print_r(string_split('123412341234', 4));

ference at super_delete_brose dot co dot uk (31-Aug-2006 08:22)

If you are looking for a way to split multibyte strings then this may come in handy:

<?php
$text 
= "süpérbr?sé";

function
mb_str_split($str, $length = 1) {
  if (
$length < 1) return FALSE;

 
$result = array();

  for (
$i = 0; $i < mb_strlen($str); $i += $length) {
   
$result[] = mb_substr($str, $i, $length);
  }

  return
$result;
}

$solo = mb_str_split($text);
$quintet = mb_str_split($text, 5);

print_r($solo);
print_r($quintet);
?>

Spits out:

Array
(
    [0] => s
    [1] => ü
    [2] => p
    [3] => é
    [4] => r
    [5] => b
    [6] => r
    [7] => ?
    [8] => s
    [9] => é
)
Array
(
    [0] => süpér
    [1] => br?sé
)

fstorm2 at gmail dot com (29-Aug-2006 10:08)

If you use PHP 4 and don't need the split_length parameter, here's the shortest replacement:

<?php

preg_split
('#(?<=.)(?=.)#s', $str);

?>

http://www.matt-fletcher.co.uk/ (21-Aug-2006 12:44)

A simple way to split credit card numbers into chunks of four numbers:

<?php
echo implode(' ',str_split($card_number,4));
?>

malmsteenforce at tlen dot pl (20-Jul-2006 06:52)

<?
//fast & short version od str_split

function string_split($str)
      {
        $str_array=array();
        $len=strlen($str);
        for($i=0;$i<$len;$i++) $str_array[]=$str{$i};
        return $str_array;
       }
//example :
var_dump (string_split("split this"));
?>

user at mockme dot com (25-Mar-2006 01:53)

found this great example on a php board for those not using php5, as an alternative to the posts below this

<?php
if(!function_exists('str_split')){
    function
str_split($string,$split_length=1){
       
$count = strlen($string); 
        if(
$split_length < 1){
            return
false
        } elseif(
$split_length > $count){
            return array(
$string);
        } else {
           
$num = (int)ceil($count/$split_length); 
           
$ret = array(); 
            for(
$i=0;$i<$num;$i++){ 
               
$ret[] = substr($string,$i*$split_length,$split_length); 
            } 
            return
$ret;
        }     
    } 
}
?>

simple (16-Mar-2006 03:54)

if (!function_exists("str_split")) {
    function str_split($string, $length = 1) {
        if ($length <= 0) {
            trigger_error(__FUNCTION__."(): The the length of each segment must be greater then zero:", E_USER_WARNING);
            return false;
        }
        $splitted  = array();
        while (strlen($string) > 0) {
            $splitted[] = substr($string, 0, $length);
            $string = substr($string, $length);
        }
        return $splitted;
    }
}

(14-Mar-2006 01:49)

Note to function by carlosreche at yahoo dot com.

The while:
<?php
...
               while (
$str_length--) {
                  
$splitted[$i] = $string[$i++];
               }
...
?>
.. result in index starting at 1.
Ie: str_split("ABC") gives
Array
(
    [1] => A
    [2] => B
    [3] => C
)
While php5's str_split("ABC") gives
Array
(
    [0] => A
    [1] => B
    [2] => C
)
And his str_split("ABC",2) gives index starting at 0.
Change to this (or something similar):
<?php
...
               while (
$str_length--) {
                  
$splitted[$i] = $string[$i];
                  
$i++;
               }
...
?>
.... or use heavyraptor's function. A bit more sclick,..

heavyraptor (10-Mar-2006 10:07)

I think that the last post by carlosreche at yahoo dot com is too complicated.
It's much easier if you do it like this:

<?php
if (!function_exists("str_split")) {
  function
str_split($str,$length = 1) {
    if (
$length < 1) return false;
   
$strlen = strlen($str);
   
$ret = array();
    for (
$i = 0; $i < $strlen; $i += $length) {
    
$ret[] = substr($str,$i,$length);
    }
    return
$ret;
  }
}
?>

I hope it helps for those with PHP <5

carlosreche at yahoo dot com (15-Feb-2006 12:23)

For those who work with PHP < 5:

<?php

if (!function_exists("str_split")) {
    function
str_split($string, $length = 1) {
        if (
$length <= 0) {
           
trigger_error(__FUNCTION__."(): The the length of each segment must be greater then zero:", E_USER_WARNING);
            return
false;
        }
       
$splitted  = array();
       
$str_length = strlen($string);
       
$i = 0;
        if (
$length == 1) {
            while (
$str_length--) {
               
$splitted[$i] = $string[$i++];
            }
        } else {
           
$j = $i;
            while (
$str_length > 0) {
               
$splitted[$j++] = substr($string, $i, $length);
               
$str_length -= $length;
               
$i += $length;
            }
        }
        return
$splitted;
    }
}

?>

Hage Yaapa (04-Feb-2006 02:27)

The very handy str_split() was introduced in PHP 5, but a lot of us are still forced to use PHP 4 at our host servers. And I am sure a lot of beginners have looked or are looking for a function to accomplish what str_split() does.

Taking advantge of the fact that strings are 'arrays' I wrote this tiny but useful e-mail cloaker in PHP, which guarantees functionality even if JavaScript is disabled in the client's browser. Watch how I make up for the lack of str_split() in PHP 4.3.10.

<?php

// cloackEmail() accepts a string, the email address to be cloaked
function cloakEmail($email) {

// We create a new array called $arChars, which will contain the individula characters making up the email address. The array is blank for now.
   
$arChars = array();

// We extract each character from the email 'exploiting' the fact that strings behave like an array: watch the '$email[$i]' bit, and beging to fill up the blank array $arChars
   
for ($i = 0; $i < strlen($email); $i++) { $arChars[] = $email[$i]; }

// Now we work on the $arChars array: extract each character in the array and print out it's ASCII value prefixed with '&#' to convert it into an HTML entity
   
foreach ($arChars as $char) { print '&#'.ord($char); }

// The result is an email address in HTML entities which, I hope most email address harvesters can't read.

}
print
cloakEmail('someone@nokikon.com');
?>

###### THE CODE ABOVE WITHOUT COMMENTS ######

<?php
function cloakEmail($email) {
   
$arChars = array();
    for (
$i = 0; $i < strlen($email); $i++) { $arChars[] = $email[$i]; }
    foreach (
$arChars as $char) { print '&#'.ord($char); }
}
print
cloakEmail('someone@nokikon.com');
?>

In creating this little utility, I demonstrated how the lack of str_split() can be made up in PHP < 5. If you got how it was accomplished, you could write a function to do exactly what str_split() does in PHP 5 and even name it 'str_split()'. :)

organek at hektor dot umcs dot lublin dot pl (21-May-2005 12:57)

[Editor's Note: Or just: php.net/wordwrap]
This is a little function to split a string into shorter strings with max lenght $n in such way, that it don't split words (it search for spaces), it's usefull for articles or sth.
Result is put in $ttab variable, and function result is number of "pages".

<?php
function divide_text($text, $n, &$ttab) {
   
   
$ttab = array();
   
$l = strlen($text); // text length
   
$cb = 0;    //copy begin from..
   
$p = 0; // parts
   
   
if ($l  <= $n) {
       
$ttab[0] = $text;
        return
1;
    } else {
       
$ctrl = 1;
        while((((
$p-1) * $n) < $l) && ($ctrl < 100)) {
       
$crtl++; // control variable, to protect from infinite loops
       
       
$tmp = substr($text, $cb, $n);
       
       
// we're looking for last space in substring
       
$lastpos = strrpos($tmp," ");   
       
        if ( (
is_bool($lastbool) && !$lastpos) || ( $l - $cb <= $n)) {
           
$ttab[$p] = $tmp;
                       
        } else  {
           
$tmpgood = trim(substr($tmp, 0,$lastpos));  // if they were another spaces at the end..
           
$ttab[$p] = $tmpgood;
           
$cb += $lastpos + 1 ;
           
        };
// if
       
$p++;
        };
//for
       
return $p;
    };
// if
   

} // divide text

?>

aidan at php dot net (20-May-2004 05:53)

This functionality is now implemented in the PEAR package PHP_Compat.

More information about using this function without upgrading your version of PHP can be found on the below link:

http://pear.php.net/package/PHP_Compat