Portrety Uliczne Nieznajomych - zobacz wyjątkową galerię portretów z warszawskich ulic
ZALOGUJ SIĘ
login:
hasło:
przypomnij hasło
załóż konto użytkownika
(i zobacz kilka porad gratis)
   
WYSZUKIWARKA I DZIAŁY
całe porady  tytuły
zaznacz działy do przeszukania
(brak wyboru = wszystkie działy)
PHP
MySQL >
PostgreSQL
SQLite
Perl
Java
XML
XSLT
XPath
WML
SVG
RegExp
Wyszukiwarki
Ochrona
VBScript
Google Plus
XHTML/CSS
JavaScript
Grafika
Flash
Photoshop
Windows
Linux
Bash
Apache
Procmail
E-biznes
Explorer
Opera
Firefox
Inne porady
   
KURSY, DOKUMENTACJE
Własne:
XHTML/CSS
JavaScript
ActionScript
WML, RSS, SSI
Pozostałe:
PHP
MySQL
Java API
więcej...
   
użytkowników online: 14
W CZYM MOGĘ POMÓC?


   
OPINIE UŻYTKOWNIKÓW
W takich dniach, jak ten, nie żałuję, że wykupiłem abonament. Korzystam z porad na tych stronach nawet kilkanaście razy w tygodniu i dzięki nim prace nad stronami dla klientów idą mi o wiele szybciej, a strony wyglądają bardziej profesjonalnie. Nie wiem, jak mogłem wcześniej pracować bez dostępu do porad w tym serwisie!

Wojciech Miszkiewicz

   
GALERIA FOTOGRAFII
   
PODRĘCZNIK PHP 5.x, 4.x, 3.x - częściowo spolszczony / źródło: www.php.net

[Spis] [A] [B] [C] [D] [E] [F] [G] [H] [I] [J] [K] [L] [M] [N] [O] [P] [Q] [R] [S] [T] [U] [V] [X] [W] [Z]

preg_split

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

preg_split -- Split string by a regular expression

Description

array 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 .

Przykład 1. preg_split() example : Get the parts of a search string

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

Przykład 2. Splitting a string into component characters

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

Przykład 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
        )

)

Notatka: 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

superzouz at hotmail dot com
04-Dec-2005 02: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 11: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 10: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 08: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 04: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 04:06

sorry, preview parses differently than the actual post :(

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


Jappie
04-Aug-2005 09: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 11: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 04: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 10: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 08:58

find duplicate words with preg_split()
http://www.michael-berndt.de/ie/tux/duplicate_words.htm


s
24-Mar-2005 06: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 05: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 05: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 07: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 11: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 10: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 03: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 08: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 01: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 09: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.


 

 
  © 1996-2012 & Reporter.plmiejscao serwisieabonamentwarunki korzystaniaRSSkontakt