|
|
 |
preg_split (PHP 3 >= 3.0.9, PHP 4, PHP 5) preg_split -- Split string by a regular expression Descriptionarray preg_split ( string pattern, string subject [, int limit [, int flags]] )
Returns an array containing substrings of
subject split along boundaries matched by
pattern.
If limit is specified, then only substrings up to
limit are returned, and if
limit is -1, it actually means "no limit", which is
useful for specifying the flags.
flags can be any combination of the following flags
(combined with bitwise | operator):
- PREG_SPLIT_NO_EMPTY
If this flag is set, only non-empty pieces will be returned by
preg_split().
- PREG_SPLIT_DELIM_CAPTURE
If this flag is set, parenthesized expression in the delimiter pattern
will be captured and returned as well. This flag was added for 4.0.5.
- PREG_SPLIT_OFFSET_CAPTURE
If this flag is set, for every occurring match the appendant string
offset will also be returned. Note that this changes the return
value in an array where every element is an array consisting of the
matched string at offset 0 and its string offset
into subject at offset 1.
This flag is available since PHP 4.3.0 .
Example 1. preg_split() example : Get the parts of a search string |
<?php
$keywords = preg_split("/[\s,]+/", "hypertext language, programming");
?>
|
|
Example 2. Splitting a string into component characters |
<?php
$str = 'string';
$chars = preg_split('//', $str, -1, PREG_SPLIT_NO_EMPTY);
print_r($chars);
?>
|
|
Example 3. Splitting a string into matches and their offsets |
<?php
$str = 'hypertext language programming';
$chars = preg_split('/ /', $str, -1, PREG_SPLIT_OFFSET_CAPTURE);
print_r($chars);
?>
|
will yield:
Array
(
[0] => Array
(
[0] => hypertext
[1] => 0
)
[1] => Array
(
[0] => language
[1] => 10
)
[2] => Array
(
[0] => programming
[1] => 19
)
) |
|
Note:
Parameter flags was added in PHP 4 Beta 3.
See also spliti(), split(),
implode(), preg_match(),
preg_match_all(), and
preg_replace().
User Contributed Notes
preg_split
richard dot lajaunie at cote-azur dot cci dot fr
18-May-2005 09:44
<?
if ( array_key_exists(1, $argv) ){
$cfgServer = $argv[1];
}else{
echo "ex: 'php test.php 10.0.0.0' \n";
exit;
}
$cfgPort = 23; $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, " "); $j = 0;
while ($j<16){
fgets($usenet, 128);
$j++;
}
stream_set_timeout($usenet, 2); $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, " "); }
$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 03:13
berndt at michael - berndt dot de
29-Apr-2005 01:58
s
23-Mar-2005 11: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);
preg_split('! and | or | not !',"blah and blarg or ick",-1,PREG_SPLIT_DELIM_CAPTURE);
?>
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 10: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 10: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 12: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 04: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 03: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 08: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 01: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 06: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 02: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.
| |