preg_split

(PHP 3 >= 3.0.9, PHP 4, PHP 5)

preg_split -- 用正则表达式分割字符串

说明

array preg_split ( string pattern, string subject [, int limit [, int flags]] )

返回一个数组,包含 subject 中沿着与 pattern 匹配的边界所分割的子串。

如果指定了 limit,则最多返回 limit 个子串,如果 limit 是 -1,则意味着没有限制,可以用来继续指定可选参数 flags

flags 可以是下列标记的任意组合(用按位或运算符 | 组合):

PREG_SPLIT_NO_EMPTY

如果设定了本标记,则 preg_split() 只返回非空的成分。

PREG_SPLIT_DELIM_CAPTURE

如果设定了本标记,定界符模式中的括号表达式也会被捕获并返回。本标记添加于 PHP 4.0.5。

PREG_SPLIT_OFFSET_CAPTURE

如果设定了本标记,如果设定本标记,对每个出现的匹配结果也同时返回其附属的字符串偏移量。注意这改变了返回的数组的值,使其中的每个单元也是一个数组,其中第一项为匹配字符串,第二项为其在 subject 中的偏移量。本标记自 PHP 4.3.0 起可用。

例子 1. preg_split() 例子

<?php
// split the phrase by any number of commas or space characters,
// which include " ", \r, \t, \n and \f
$keywords = preg_split ("/[\s,]+/", "hypertext language, programming");
?>

例子 2. 将字符串分割成字符

<?php
$str
= 'string';
$chars = preg_split('//', $str, -1, PREG_SPLIT_NO_EMPTY);
print_r($chars);
?>

例子 3. 将字符串分割为匹配项及其偏移量

<?php
$str
= 'hypertext language programming';
$chars = preg_split('/ /', $str, -1, PREG_SPLIT_OFFSET_CAPTURE);
print_r($chars);
?>

本例将输出:

Array
(
    [0] => Array
        (
            [0] => hypertext
            [1] => 0
        )

    [1] => Array
        (
            [0] => language
            [1] => 10
        )

    [2] => Array
        (
            [0] => programming
            [1] => 19
        )

)

注: flags 是 PHP 4 Beta 3 添加的。

参见 spliti()split()implode()preg_match()preg_match_all()preg_replace()


add a note add a note User Contributed Notes
be2 dot php dot net at alan-smith dot no-ip dot com
01-Sep-2006 02:42
This script changes 1 line to multi-lines, with $max_size as the max size of the line.

<?
$max_size
= 70
$str
= "Test - Test - Test - Test - Test - Test - Test - Test - Test - Test - Test - Test - Test - Test - Test - Test - Test - Test - Test - Test - Test - Test";
$keywords = preg_split("/[\s,]+/", $str, -1, PREG_SPLIT_OFFSET_CAPTURE);

foreach(
$keywords as $msg){
$line[(floor($msg[1]/$max_size))].= $msg[0].' ';
}
print_r ($line);

//Array
//(
//    [0] => Test - Test - Test - Test - Test - Test - Test - Test - Test - Test -
//    [1] => Test - Test - Test - Test - Test - Test - Test - Test - Test - Test -
//    [2] => Test - Test
//)

?>
superzouz at hotmail dot com
04-Dec-2005 09:53
Be advised

$arr = preg_split("/x/", "x" );
print_r($arr);

will output:

Array
(
   [0] =>
   [1] =>
)

That is it will catch the 2 empty string on each side of the delimiter.
19-Oct-2005 05:30
<?php
$a
='BlackHalt';
$b=preg_split('//',$a,-1,PREG_SPLIT_DELIM_CAPTURE);
echo
join(' ',$b);
?>
result:
 B l a c k H a l t
nospam at emails dot com
11-Oct-2005 04:55
Looks like this one looks better :)
<?php
$pattern
= '/(<(?:[^<>]+(?:"[^"]*"|\'[^\']*\')?)+>)/';
$html_string = '<html><body><p class="a<weird>name">The classname is not seen as a different tag</p></body></html>';
$html_array = preg_split ($pattern, trim ($html_string), -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
?>
ia [AT] zoznam [DOT] sk
19-Sep-2005 02:50
to afterlife69 [at] GamerzVault.com:

wouldn't it be better to use just
<?php
$str
= sha1( 'string' );
echo
substr( $str, 0, 32 );
?>
???
afterlife69 [at] GamerzVault.com
21-Aug-2005 10:50
This is something ive needed for awhile, a way to limit the length of a string.

<?php
function limit_length($string, $length)
{
  
$chars = preg_split('//', $string, -1, PREG_SPLIT_NO_EMPTY);
   for(
$i = 0; $i < intval($length); $i++)
   {
       if(!empty(
$new_str))
       {
          
$new_str .= $chars[$i];
       }
       else
       {
          
$new_str = $chars[$i];
       }
   }
   return
$new_str;
}

$str = sha1('string');
echo
limit_length($str, 32);

?>

32Char SHA1 will trick them anyday ^^
Jappie
06-Aug-2005 10:06
sorry, preview parses differently than the actual post :(

<?php
  $pattern
= '/(<(?:[^<>]+(?:"[^"]*"|\'[^\']*\')?)+>)/';
?>
Jappie
05-Aug-2005 03:36
The following pattern will match a html tag:

<?php
  $pattern
= '/(<(?:[^<>]+(?:"[^"]*"|\\'[^']*\\')?)+>)/';
?>

So the following will nicely convert a string of html to an array, where each array-item is 1 tag or text within a tag:

<?php
  $html_string = '
<html><body><p class="a<weird>name">The classname is not seen as a different tag</p></body></html>';
  $html_array = preg_split ('
/(<(?:[^<>]+(?:"[^"]*"|\\'[^\\']*\\')?)+>)/', trim ($html), -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
?>

Array
(
   [0] => <html>
   [1] => <body>
   [2] => <p class="
a<weird>name">
   [3] => The classname is not seen as a different tag
   [4] => </p>
   [5] => </body>
   [6] => </html>

)
RichardWalton1978@hotmaildotcom
22-Jul-2005 05:59
I have been searching for a method to get the IP details from a unix based (solaris) interface and found this to be useful.

$devicen = "iprb1";

$temp = preg_split("/[\s]+/",shell_exec("/sbin/ifconfig $devicen | /bin/grep \"inet\""), -1, PREG_SPLIT_NO_EMPTY);

$ipaddress = $temp[1];
$netmask = $temp[3];
$gateway = $temp[5];

print_r ($temp);
print "<BR>This is the current IP Address: $ipaddress<BR>
this is the current netmask: $netmask<BR>
this is the current default gateway $gateway<BR>";
richard dot lajaunie at cote-azur dot cci dot fr
18-May-2005 10:44
<?
/************************************************************
* Author: Richard Lajaunie
* Mail : richard.lajaunie@cote-azur.cci.fr
*
* subject : this script retreive all mac-addresses on all ports
* of a Cisco 3548 Switch by a telnet connection
*
* base on the script by: xbensemhoun at t-systems dot fr on the same page
**************************************************************/

if ( array_key_exists(1, $argv) ){
  
$cfgServer = $argv[1];
}else{
   echo
"ex: 'php test.php 10.0.0.0' \n";
   exit;
}

$cfgPort    = 23;                //port, 22 if SSH
$cfgTimeOut = 10;

$usenet = fsockopen($cfgServer, $cfgPort, $errno, $errstr), $cfgTimeOut);

if(!
$usenet){
       echo
"Connexion failed\n";
       exit();
}else{
       echo
"Connected\n";
      
fputs ($usenet, "password\r\n");
      
fputs ($usenet, "en\r\n");
      
fputs ($usenet, "password\r\n");
      
fputs ($usenet, "sh mac-address-table\r\n");
      
fputs ($usenet, " "); // this space bar is this for long output
      
       // this skip non essential text
      
$j = 0;
       while (
$j<16){
      
fgets($usenet, 128);
      
$j++;
       }
  
stream_set_timeout($usenet, 2); // set the timeout for the fgets
  
$j = 0;
       while (!
feof($usenet)){
      
$ret = fgets($usenet, 128);
      
$ret = str_replace("\r", '', $ret);
      
$ret = str_replace("\n", "", $ret);
       if  (
ereg("FastEthernet", $ret)){
           echo
"$ret \n";
       }
       if (
ereg('--More--', $ret) ){
          
fputs ($usenet, " "); // for following page
      
}
      
$info = stream_get_meta_data($usenet);
       if (
$info['timed_out']) {
          
$j++;
       }
       if (
$j >2){
          
fputs ($usenet, "lo");
           break;
       }
   }
}
echo
"End.\r\n";
?>
berndt at www dot michael - berndt dot de
30-Apr-2005 04:13
FindDuplicatesPosition() with preg_split()
http://www.michael-berndt.de/ie/tux/duplicate_words_position.htm
berndt at michael - berndt dot de
30-Apr-2005 02:58
find duplicate words with preg_split()
http://www.michael-berndt.de/ie/tux/duplicate_words.htm
s
24-Mar-2005 01:22
'galium at sandnarrows dot com' misunderstanded.
he wrote ' Notice the delimiters are missing', but the delimiters are not missing.
when using preg_*() functions, you need to quote pattern with 'delimiters', for example '/', '#', '@', or '(' and ')'.
in the context of preg_split(), 'the delimiters' means both,
 (A)delimiters of pattern - which quote pattern
 (B)delimiter pattern    - which split the string to array

in his first code,
<?php
  preg_split
('( and | or | not )',"blah and blarg or ick",-1,PREG_SPLIT_DELIM_CAPTURE);
?>
the '(' and ')' is a delimiter of pattern strings(A). this is same as...
<?php
  preg_split
('/ and | or | not /',"blah and blarg or ick",-1,PREG_SPLIT_DELIM_CAPTURE);
 
// or
 
preg_split('! and | or | not !',"blah and blarg or ick",-1,PREG_SPLIT_DELIM_CAPTURE);
 
// and so on...
?>
so, It returns: Array ( [0] => blah [1] => blarg [2] => ick ). (there is no doubt nor any bugs)
the delimiters(A) are not missing. and the delimiter pattern(B) is ' and | or | not'.

then, in the following code...
<?php
  preg_split
('(( and )|( or )|( not ))',"blah and blarg or ick",-1,PREG_SPLIT_DELIM_CAPTURE);
?>
the first '(', and last ')' is a delimiter of pattern strings, and second, third, firth '(' and ')' make subpatterns('parenthesized expression').
this is same as...
<?php
  preg_split
('/( and )|( or )|( not )/',"blah and blarg or ick",-1,PREG_SPLIT_DELIM_CAPTURE);
?>
and so on...
the delimiters(A) are not missing. and the delimiter pattern(B) is '( and )|( or )|( not)' ( this is same as ' (and|or|not) ').

Sorry for my bad English. ( can you understand?)
hope this can help some one.
and also hope, some one rewite this to good English.
Steve
24-Mar-2005 12:41
preg_split() behaves differently from perl's split() if the string ends with a delimiter. This perl snippet will print 5:

my @a = split(/ /, "a b c d e ");
print scalar @a;

The corresponding php code prints 6:

print count(preg_split("/ /", "a b c d e "));

This is not necessarily a bug (nowhere does the documentation say that preg_split() behaves the same as perl's split()) but it might surprise perl programmers.
jetsoft at iinet.net.au
25-Sep-2004 11:01
To clarify the "limit" parameter and the PREG_SPLIT_DELIM_CAPTURE option,

$preg_split('(/ /)', '1 2 3 4 5 6 7 8', 4 ,PREG_SPLIT_DELIM_CAPTURE );
returns

('1', ' ', '2', ' ' , '3', ' ', '4 5 6 7 8')

So you actually get 7 array items not 4
tuxedobob
25-Sep-2004 01:24
The documentation for the "limit" parameter may be slightly confusing. "limit" does indeed work like the limit of explode, in that the "limit"th substring will contain the rest of the string passed, _not_ that it will split it fully and return only the first "limit"th strings. Therefore:

$preg_split('/ /', '1 2 3 4 5 6 7 8 9', 4);

returns

('1', '2', '3', '4 5 6 7 8 9')

and _not_

('1', '2', '3', '4').

Although explode has an example of this, there is none here.
e at arix dot com
19-Jul-2004 05:51
I needed a function to highlight strings in a piece of text that could be marked up.  the task couldn't be accomplished with a single preg_replace so I wrote the code below which processes only the parts of the text _outside_ markup tags.

for example: with the text:

click on <a href="nowhere.html">nothing</a>!

I wanted to "highlight" a string (e.g. "no"), producing:

click on <a href="nowhere.html"><span class="hilite">no</span>thing</a>!

and not:

click on <a href="<span class="hilite">no</span>where.html"><span class="hilite">no</span>thing</a>!

hope this helps someone!

<?php
function hilites($search, $txt) {
  
$r = preg_split('((>)|(<))', $txt, -1, PREG_SPLIT_DELIM_CAPTURE);
   for (
$i = 0; $i < count($r); $i++) {
       if (
$r[$i] == "<") {
          
$i++; continue;
           }
      
$r[$i] = preg_replace(
          
"/($search)/i", "<span class='hilite'>\\1</span>", $r[$i]
           );
       }
   return
join("", $r);
   }
?>
ed_isthmusNOSPAM at yahoo dot com
07-Feb-2004 05:26
I needed to encode special html characters in strings, but keep some of the tags working! This function does the deed:
<?php
function html_out_keep_tags ($string) {
 
$newstring = '';
 
$pattern = '/(<\/?(?:a .*|h1|h2|b|i)>)/ims';
 
$newarray = preg_split( $pattern, $string, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY );
  foreach (
$newarray as $element) {
   if (!
preg_match($pattern, $element))
    
$element = htmlspecialchars ( html_entity_decode($element, ENT_QUOTES), ENT_QUOTES);
  
$newstring .= $element;
  }
  return
$newstring;
}
?>
edit $pattern to change the allowed tags.
Note that ?: usefully prevents the sub-pattern from becoming a delimiter. Double encoding is prevented, see notes on htmlspecialchars().
galium at sandnarrows dot com
29-Oct-2003 10:15
Struggled with this today and just thought I would toss out a note in case anyone else has a problem. When using PREG_SPLIT_DELIM_CAPTURE the note about parenthesized expression is rather important.

If you do: preg_split('( and | or | not )',"blah and blarg or ick",-1,PREG_SPLIT_DELIM_CAPTURE);

It returns: Array ( [0] => blah [1] => blarg [2] => ick )

Notice the delimiters are missing.

If you put extra () in: preg_split('(( and )|( or )|( not ))',"blah and blarg or ick",-1,PREG_SPLIT_DELIM_CAPTURE);

It returns: Array ( [0] => blah [1] => and [2] => blarg [3] => [4] => or [5] => ick )
Shelby Moore III
29-Aug-2003 02:32
Note when using PREG_SPLIT_DELIM_CAPTURE, "limit" does include the count of parenthesized delimiter strings returned.

More succinctly, if "limit" != 1, "limit" / 2 is the maximum number of splits you allow.
redph0enix at hotmail dot com
18-Mar-2003 08:52
preg_split is very useful for splitting up the http common log. Sample:

<?php
$line
= '10.0.0.2 - - [17/Mar/2003:18:03:08 +1100] "GET /images/org_background.gif HTTP/1.0" 200 2321 "http://10.0.0.3/login.php" "Mozilla/5.0 Galeon/1.2.7 (X11; Linux i686; U;) Gecko/20021203"';

$elements = preg_split('/^(\S+) (\S+) (\S+) \[([^\]]+)\] "([^"]+)" (\S+) (\S+) "([^"]+)" "([^"]+)"/', $line,-1,PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);

print_r($elements);
?>

Results:
Array
(
   [0] => 10.0.0.2
   [1] => -
   [2] => -
   [3] => 17/Mar/2003:18:03:08 +1100
   [4] => GET /images/org_background.gif HTTP/1.0
   [5] => 200
   [6] => 2321
   [7] => http://10.0.0.3/login.php
   [8] => Mozilla/5.0 Galeon/1.2.7 (X11; Linux i686; U;) Gecko/20021203
)
dave at codewhore dot org
30-May-2002 03:01
The above description for PREG_SPLIT_OFFSET_CAPTURE may be a bit confusing.

When the flag is or'd into the 'flags' parameter of preg_split, each match is returned in the form of a two-element array. For each of the two-element arrays, the first element is the matched string, while the second is the match's zero-based offset in the input string.

For example, if you called preg_split like this:

preg_split('/foo/', 'matchfoomatch', -1, PREG_SPLIT_OFFSET_CAPTURE);

it would return an array of the form:

Array(
  [0] => Array([0] => "match", [1] => 0),
  [1] => Array([1] => "match", [1] => 8)
)

Note that or'ing in PREG_DELIM_CAPTURE along with PREG_SPLIT_OFFSET_CAPTURE works as well.