search for in the  
<eregispliti>
Last updated: Thu, 19 May 2005

split

(PHP 3, PHP 4, PHP 5)

split -- Split string into array by regular expression

Description

array split ( string pattern, string string [, int limit] )

Tip: preg_split(), which uses a Perl-compatible regular expression syntax, is often a faster alternative to split(). If you don't require the power of regular expressions, it is faster to use explode(), which doesn't incur the overhead of the regular expression engine.

Returns an array of strings, each of which is a substring of string formed by splitting it on boundaries formed by the case-sensitive regular expression pattern. If limit is set, the returned array will contain a maximum of limit elements with the last element containing the whole rest of string. If an error occurs, split() returns FALSE.

To split off the first four fields from a line from /etc/passwd:

Example 1. split() example

<?php
list($user, $pass, $uid, $gid, $extra) =
  
split(":", $passwd_line, 5);
?>

If there are n occurrences of pattern, the returned array will contain n+1 items. For example, if there is no occurrence of pattern, an array with only one element will be returned. Of course, this is also true if string is empty.

To parse a date which may be delimited with slashes, dots, or hyphens:

Example 2. split() example

<?php
// Delimiters may be slash, dot, or hyphen
$date = "04/30/1973";
list(
$month, $day, $year) = split('[/.-]', $date);
echo
"Month: $month; Day: $day; Year: $year<br />\n";
?>

For users looking for a way to emulate Perl's @chars = split('', $str) behaviour, please see the examples for preg_split().

Please note that pattern is a regular expression. If you want to split on any of the characters which are considered special by regular expressions, you'll need to escape them first. If you think split() (or any other regex function, for that matter) is doing something weird, please read the file regex.7, included in the regex/ subdirectory of the PHP distribution. It's in manpage format, so you'll want to do something along the lines of man /usr/local/src/regex/regex.7 in order to read it.

See also: preg_split(), spliti(), explode(), implode(), chunk_split(), and wordwrap().



User Contributed Notes
split
wchris
18-Feb-2005 05:53
moritz's quotesplit didn't work for me. It seemed to split on a comma even though it was between a pair of quotes. However, this did work:

function quotesplit($s, $splitter=',')
{
//First step is to split it up into the bits that are surrounded by quotes and the bits that aren't. Adding the delimiter to the ends simplifies the logic further down

   $getstrings = split('\"', $splitter.$s.$splitter);

//$instring toggles so we know if we are in a quoted string or not
   $delimlen = strlen($splitter);
   $instring = 0;

   while (list($arg, $val) = each($getstrings))
   {
       if ($instring==1)
       {
//Add the whole string, untouched to the result array.
           $result[] = $val;
           $instring = 0;
       }
       else
       {
//Break up the string according to the delimiter character
//Each string has extraneous delimiters around it (inc the ones we added above), so they need to be stripped off
           $temparray = split($splitter, substr($val, $delimlen, strlen($val)-$delimlen-$delimlen ) );

           while(list($iarg, $ival) = each($temparray))
           {
               $result[] = trim($ival);
           }
           $instring = 1;
       }
   }
   return $result;
}
ramkumar rajendran
17-Jan-2005 12:09
A correction to a earlier note
If you want to use split to check on line feeds (\n), the following won't work:

$line = split("\n", $input_several_lines_long);

You really have to do this instead, notice the second slash:
$line = split("/\n", $input_several_lines_long);

Took me a little while to figure to do
claes at dot2me.com
03-Nov-2004 06:10
Though this is obvious, the manual is a bit incorrect when claiming that the return will always be 1+number of time the split pattern occures.  If the split pattern is the first part of the string, the return will still be 1.  E.g.

$a = split("zz," "zzxsj.com");
count($a);

=> 1.

The return of this can not in anyway be seperated from the return where the split pattern is not found.
moritz
09-Apr-2004 01:54
Often you want to split CSV-Like data, so this is the function for this :)

It splits data formatted like:

1,2,3
-> [1,2,3]

1 , 3, 4
-> [1,3,4]

one; two;three
-> ['one','two','three']

"this is a string", "this is a string with , and ;", 'this is a string with quotes like " these', "this is a string with escaped quotes \" and \'.", 3
-> ['this is a string','this is a string with , and ;','this is a string with quotes like " these','this is a string with escaped quotes " and '.',3]

function quotesplit($s)
{
   $r = Array();
   $p = 0;
   $l = strlen($s);
   while ($p < $l) {
       while (($p < $l) && (strpos(" \r\t\n",$s[$p]) !== false)) $p++;
       if ($s[$p] == '"') {
           $p++;
           $q = $p;
           while (($p < $l) && ($s[$p] != '"')) {
               if ($s[$p] == '\\') { $p+=2; continue; }
               $p++;
           }
           $r[] = stripslashes(substr($s, $q, $p-$q));
           $p++;
           while (($p < $l) && (strpos(" \r\t\n",$s[$p]) !== false)) $p++;
           $p++;
       } else if ($s[$p] == "'") {
           $p++;
           $q = $p;
           while (($p < $l) && ($s[$p] != "'")) {
               if ($s[$p] == '\\') { $p+=2; continue; }
               $p++;
           }
           $r[] = stripslashes(substr($s, $q, $p-$q));
           $p++;
           while (($p < $l) && (strpos(" \r\t\n",$s[$p]) !== false)) $p++;
           $p++;
       } else {
           $q = $p;
           while (($p < $l) && (strpos(",;",$s[$p]) === false)) {
               $p++;
           }
           $r[] = stripslashes(trim(substr($s, $q, $p-$q)));
           while (($p < $l) && (strpos(" \r\t\n",$s[$p]) !== false)) $p++;
           $p++;
       }
   }
   return $r;
}
alphibia at alphibia dot com
31-Mar-2004 08:19
I'd like to correct myself, I found that after testing my last solution it will create 5 lines no matter what... So I added this to make sure that it only displays 5 if there are five newlines. :-)

<?php
   $MaxNewLines
= 5;

  
$BRCount = substr_count($Message, '<br />'); 
   if (
$BRCount<$MaxNewLines)
  
$MaxNewLines=$BRCount;
   else if(
$BRCount == 0)
  
$MaxNewLines=1;

  
$Message = str_replace(chr(13), "<br />", $Message);
  
$MessageArray = split("<br />", $Message, $MaxNewLines);
  
$Message = ""; $u=0;
   do    {
  
$Message.=$MessageArray[$u].'<br />';
  
$u++;
   } while(
$u<($MaxNewLines-1));
  
$Message.=str_replace("<br />"," ",$MessageArray[$u]);
  
?>

-Tim
http://www.alphibia.com
nomail at please dot now
21-Nov-2003 11:33
If you want to use split to check on line feeds (\n), the following won't work:

$line = split("\n", $input_several_lines_long);

You really have to do this instead, notice the second slash:
$line = split("\\n", $input_several_lines_long);

Took me a little while to figure out.
krahn at niehs dot nih dot gov
24-Oct-2003 02:14
> strange things happen with split
> this didn't work
> $vontag $vonmonat were empty strings
...
> list ($vontag , $vonmonat) = split ('.' , $fromdate); // << bad

Split is acting exactly as it should; it splits on regular expressions.
A period is a regular expression pattern for a single character.
So, an actual period must be escaped with a backslash:  '\.'
A period within brackets is not an any-character pattern, because it does
not make sense in that context.

Beware that regular expressions can be confusing becuase there
are a few different varieties of patterns.
dalu at uni dot de
08-Oct-2003 02:26
php4.3.0

strange things happen with split

this didn't work
$vontag $vonmonat were empty strings

<?php
function ckdate($fromdate="01.01", $todate="31.12")
{
  
$nowyear = date("Y");
   list (
$vontag , $vonmonat) = split ('.' , $fromdate); // << bad
  
$vondatum = "$nowyear-$vonmonat-$vontag";
   list (
$bistag , $bismonat) = split ('.' , $todate); // << bad
  
$bisdatum = "$nowyear-$bismonat-$bistag";
  
$von = strtotime($vondatum);
  
$bis = strtotime($bisdatum);
  
$now = time();
   if ((
$now <= $bis) and ($now >= $von))
   {
       return
TRUE;
   }
   else
   {
       return
FALSE;
   }
}
?>

however this one worked perfectly

<?php
function ckdate($fromdate="01.01", $todate="31.12")
{
  
$nowyear = date("Y");
   list (
$vontag , $vonmonat) = split ('[.]' , $fromdate); // << good
  
$vondatum = "$nowyear-$vonmonat-$vontag";
   list (
$bistag , $bismonat) = split ('[.]' , $todate); // << good
  
$bisdatum = "$nowyear-$bismonat-$bistag";
  
$von = strtotime($vondatum);
  
$bis = strtotime($bisdatum);
  
$now = time();
   if ((
$now <= $bis) and ($now >= $von))
   {
       return
TRUE;
   }
   else
   {
       return
FALSE;
   }
}
?>

btw this fn checks if $now if between $fromdate and $todate
use it if you like
jeffrey at jhu dot edu
10-Jan-2003 03:51
In answer to gwyne at gmx dot net, dec 1, 2002:

For split(), when using a backslash as the delimiter, you have to *double escape* the backslash.

example:
==================================
<pre>
<?
$line
= 'stuff\\\thing\doodad\\';
$linearray = split('\\\\', $line); //<--NOTE USE OF FOUR(4)backslashes
print join(":", $linearray);
?>
</pre>

==================================
output is:

<pre>
stuff::thing:doodad:
</pre>
paha at paha dot hu
21-Jul-2002 08:51
It's evident but not mentioned in the documentation that using asterisks is more restricted than in a normal regular expression.

for exaple you cannot say:

split(";*",$string);

because what if there's no ";" separator?(which is covered by this regular expression)

so you have to use at least

split(";+",$quotatxt);

in this situation.
fotw at gmx dot net
17-Jun-2002 02:50
Ups! It seems that neither explode nor split REALY takes a STRING but only a single character as a string for splitting the string.
 I found this problem in one of my codes when trying to split a string using ";\n" as breaking string. The result, only ";" was thaken... the rest of the string was ignored.
 Same when I tried to substitute "\n" by any other thing. :(
not at anythingspecial dot com
16-Jun-2002 08:48
If you need to do a split on a period make sure you escape the period out..

$ext_arr = split("\.","something.jpg");
... because
$ext_arr = split(".","something.jpg"); won't work properly.
kang at elpmis dot com
12-Jun-2002 01:30
This is a good way to display a comma delimited file with two columns.  The first column is the URL's description, the second is the actual URL.

<ul>
<?php
  $fname
="relatedlinks.csv";
 
$fp=fopen($fname,"r") or die("Error found.");
 
$line = fgets( $fp, 1024 );
  while(!
feof($fp))
  {
   list(
$desc,$url,$dummy) = split( ",", $line, 3 );
   print
"<li>";
   print
"<a href='$url'>$desc</a>";
   print
"</li>\n";
  
$line = fgets( $fp, 1024 );
  }
 
fclose($fp);
?>
</ul>
jchart at sdccu dot net
31-May-2002 02:56
[Ed. note: Close. The pipe *is* an operator in PHP, but
the reason this fails is because it's also an operator
in the regex syntax. The distinction here is important
since a PHP operator inside a string is just a character.]

The reason your code:

$line = "12|3|Fred";
list ($msgid, $msgref, $msgtopic)=split('|', $line);

didn't work is because the "|" symbol is an operator in PHP. If you want to use the pipe symbol as a delimiter you must excape it with a back slash, "\|". You code should look like this:

$line = "12|3|Fred";
list ($msgid, $msgref, $msgtopic)=split('\|', $line);
mcgarry at tig dot com dot au
17-May-2002 05:27
split() doesn't like NUL characters within the string, it treats the first one it meets as the end of the string, so if you have data you want to split that can contain a NUL character you'll need to convert it into something else first, eg:

$line=str_replace(chr(0),'',$line);

<eregispliti>
 Last updated: Thu, 19 May 2005
Copyright © 2001-2005 The PHP Group
All rights reserved.
This unofficial mirror is operated at: The Server Pages
Last updated: Thu May 19 17:35:34 2005 CDT