Deprecated: The each() function is deprecated. This message will be suppressed on further calls in /home/zhenxiangba/zhenxiangba.com/public_html/phproxy-improved-master/index.php on line 456
PHP: preg_split - Manual
[go: Go Back, main page]

PHP
downloads | documentation | faq | getting help | mailing lists | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

PDF 関数" width="11" height="7"/> <preg_replace
Last updated: Mon, 05 Feb 2007

view this page in

preg_split

(PHP 4, PHP 5)

preg_split — 正規表現で文字列を分割する

説明

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

指定した文字列を、正規表現で分割します。

パラメータ

pattern

検索するパターンを表す文字列。

subject

入力文字列。

limit

これを指定した場合、最大 limit 個の部分文字列が返されます。そして、 limit が -1 の場合は「制限が無い」ことを意味します。 これは、flags を指定する場合に有用です。

flags

flags は、次のフラグを組み合わせたものとする (ビット和演算子|で組み合わせる)ことが可能です。

PREG_SPLIT_NO_EMPTY
このフラグを設定すると、空文字列でないものだけが preg_split() により返されます。
PREG_SPLIT_DELIM_CAPTURE
このフラグを設定すると、文字列分割用のパターン中の カッコによるサブパターンでキャプチャされた値も同時に返されます。
PREG_SPLIT_OFFSET_CAPTURE

このフラグを設定した場合、各マッチに対応する文字列のオフセットも返されます。 これにより、返り値は配列となり、配列の要素 0 はマッチした文字列、 要素 1subject におけるマッチした文字列のオフセット値となることに 注意してください。

返り値

pattern にマッチした境界で分割した subject の部分文字列の配列を返します。

変更履歴

バージョン説明
4.3.0 PREG_SPLIT_OFFSET_CAPTURE が追加されました。
4.0.5 PREG_SPLIT_DELIM_CAPTURE が追加されました。
4 Beta 3 パラメータ flags が追加されました。

例 1627. preg_split() の例 : 検索文字列のある部分を取得

<?php
// カンマまたは " ", \r, \t, \n , \f などの空白文字で句を分割する。
$keywords = preg_split("/[\s,]+/", "hypertext language, programming");
?>

例 1628. 文字列を文字要素に分割

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

例 1629. 文字列をマッチするものとそのオフセットに分割

<?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
        )

)

    

注意

ティップ

正規表現の威力を必要としないのなら、より高速な (機能はシンプルですが) 代替関数として explode() あるいは str_split() のような選択肢があります。

参考

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



add a note add a note User Contributed Notes
preg_split
me
14-Nov-2006 10:56
This script splits a text into portions of a defined max. size, which will never be exceeded, and doesnt cut words. (Per portion it adds as many words as possible without exceeding the char-limit)

the only exception where a portion would be bigger than the limit, is when there's a word thats longer than the max_size, but you could quite easily change the script so it regards this.

<?
$str
= 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.';

$max_size = 50;
$words = preg_split("/[\040]+/", $str, -1);

$r=0;
for(
$i=0; $i < count($words); $i++) {
if (
strlen($line[$r] . $words[$i] . ' ') < $max_size) $line[$r] .= $words[$i] . ' ';
else
   {
      
$r++;
      
$line[$r] .= $words[$i] . ' ';
   }
}
print_r ($line);
?>

Result:

Array
(
   [0] => Lorem ipsum dolor sit amet, consectetur
   [1] => adipisicing elit, sed do eiusmod tempor
   [2] => incididunt ut labore et dolore magna aliqua. Ut
   [3] => enim ad minim veniam, quis nostrud exercitation
   [4] => ullamco laboris nisi ut aliquip ex ea commodo
   [5] => consequat. Duis aute irure dolor in
   [6] => reprehenderit in voluptate velit esse cillum
   [7] => dolore eu fugiat nulla pariatur. Excepteur sint
   [8] => occaecat cupidatat non proident, sunt in culpa
   [9] => qui officia deserunt mollit anim id est laborum.
)
be2 dot php dot net at alan-smith dot no-ip dot com
01-Sep-2006 03: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 10: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 06: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 05: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 03: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 11: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 11:06
sorry, preview parses differently than the actual post :(

<?php
  $pattern
= '/(<(?:[^<>]+(?:"[^"]*"|\'[^\']*\')?)+>)/';
?>
Jappie
05-Aug-2005 04: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 06: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 11: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 05: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 03:58
find duplicate words with preg_split()
http://www.michael-berndt.de/ie/tux/duplicate_words.htm
s
24-Mar-2005 02: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 01: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
26-Sep-2004 12: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 02: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 06: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 06: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 11: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 03: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 09: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 04: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.

PDF 関数" width="11" height="7"/> <preg_replace
Last updated: Mon, 05 Feb 2007
 
 
show source | credits | sitemap | contact | advertising | mirror sites