|
|
 |
split (PHP 3, PHP 4 , PHP 5) split -- 用正则表达式将字符串分割到数组中 说明array split ( string pattern, string string [, int limit]) 提示:
preg_split() 函数使用了
Perl 兼容正则表达式语法,通常是比
split() 更快的替代方案。如果不需要正则表达式的威力,则使用
explode() 更快,这样就不会招致正则表达式引擎的浪费。
本函数返回一个字符串数组,每个单元为
string 经区分大小写的正则表达式
pattern 作为边界分割出的子串。如果设定了
limit,则返回的数组最多包含
limit 个单元,而其中最后一个单元包含了
string 中剩余的所有部分。如果出错,则
split() 返回 FALSE。
将 /etc/passwd 中的前四个字段分割出来:
例子 1. split() 例子 |
<?php
list($user, $pass, $uid, $gid, $extra) =
split (":", $passwd_line, 5);
?>
|
|
如果字符串中有 n 个与
pattern 匹配的项目,则返回的数组将包含
n+1 个单元。例如,如果没有找到
pattern,则会返回一个只有一个单元的数组。当然,如果
string 为空也是这样。
解析可能用斜线,点,或横线分割的日期:
例子 2. split() 例子 |
<?php
$date = "04/30/1973";
list($month, $day, $year) = split ('[/.-]', $date);
echo "Month: $month; Day: $day; Year: $year<br />\n";
?>
|
|
想仿效 Perl 中类似的 @chars =
split('', $str) 行为,请参考
preg_split() 函数中的例子。
注意 pattern
是一个正则表达式。如果想要用的分割字符是正则表达式中的特殊字符,要先将其转义。如果觉得
split()(或其它任何 regex 函数)行为古怪的话,请阅读包含在
PHP 发行包中 regex/ 子目录下的
regex.7 文件。该文件是手册页面格式,可以用类似
man /usr/local/src/regex/regex.7 的命令来阅读。
参见 preg_split(),spliti(),explode(),implode(),chunk_split()
和 wordwrap()。
wchris
18-Feb-2005 12: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 07: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
04-Nov-2004 01: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 08: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 04: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 06: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 09: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 09: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); $vondatum = "$nowyear-$vonmonat-$vontag";
list ($bistag , $bismonat) = split ('.' , $todate); $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); $vondatum = "$nowyear-$vonmonat-$vontag";
list ($bistag , $bismonat) = split ('[.]' , $todate); $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 10: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); print join(":", $linearray);
?>
</pre>
==================================
output is:
<pre>
stuff::thing:doodad:
</pre>
paha at paha dot hu
22-Jul-2002 03: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 09: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
17-Jun-2002 03: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 08: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='/old?u=http%3A%2F%2Ffr.php.net%2Fmanual%2Fzh%2F%24url&y=1999'>$desc</a>";
print "</li>\n";
$line = fgets( $fp, 1024 );
}
fclose($fp);
?>
</ul>
jchart at sdccu dot net
31-May-2002 09: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 12: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);
| |