PHP: preg_split - Manual

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

search for in the

PDF preg_replace

Last updated: Sat, 27 Jan 2007

view this page in

# 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`

  В случае, если этот флаг указан, для каждой найденной подстроки, будет указана ее позиция в исходной строке. Необходимо помнить, что этот флаг меняет формат возвращаемых данных: каждое вхождение возвращается в виде массива, в нулевом элементе которого содержится найденная подстрока, а в первом - смещение.

Пример 1. preg_split() пример: Получение подстрок из заданного текста

`<?php // разбиваем строку по произвольному числу запятых и пробельных символов, // которые включают в себя " ", \r, \t, \n и \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 User Contributed Notes
preg_split
23-Feb-2007 10:01
`Actually I meant to say separated a stream based on commas and SPACES, not quotes.`
Tony
16-Feb-2007 07:32
`Thanks to "s" I figured out how to split a sentence based on commas and quotes, without losing the commas and quotes. It requires the addition of parenthesis to the expression, leaving me with what I call the "breast" split:
preg_split("((,)|( ))", $mystring, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
Okay obviously that SHOULD be "((,)|(\s))", but both work.
For the phrase: "you, and"
You end up with:
you
,
and`
me
14-Nov-2006 05: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
31-Aug-2006 11: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 05: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.`
18-Oct-2005 02: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
10-Oct-2005 01: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
18-Sep-2005 11: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 07: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 07:06
`sorry, preview parses differently than the actual post :(
<?php
$pattern = '/(<(?:[^<>]+(?:"[^"]*"|\'[^\']*\')?)+>)/';
?>`
Jappie
04-Aug-2005 12: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 02: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 07: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 01:13
`FindDuplicatesPosition() with preg_split()
http://www.michael-berndt.de/ie/tux/duplicate_words_position.htm`
berndt at michael - berndt dot de
29-Apr-2005 11:58
`find duplicate words with preg_split()
http://www.michael-berndt.de/ie/tux/duplicate_words.htm`
s
23-Mar-2005 09: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
23-Mar-2005 08: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 08: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
24-Sep-2004 10: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
18-Jul-2004 02: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
06-Feb-2004 01: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
28-Oct-2003 06: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
28-Aug-2003 11: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 04: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
29-May-2002 12: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.`
add a note
PDF preg_replace

Last updated: Sat, 27 Jan 2007
show source | credits | stats | sitemap | contact | advertising | mirror sites
Copyright © 2001-2007 The PHP Group
All rights reserved.
This mirror generously provided by: Yahoo! Inc.
Last updated: Sat Mar 10 09:32:46 2007 PST