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

search for in the

BBCode> <PCRE Funktionen
Last updated: Fri, 11 Apr 2008

view this page in

preg_split

(PHP 4, PHP 5)

preg_split — Zerlegt eine Zeichenkette anhand eines regulären Ausdrucks

Beschreibung

array preg_split ( string $Suchmuster , string $Zeichenkette [, int $Limit [, int $Flags ]] )

Zerlegt die angegebene Zeichenkette anhand eines regulären Ausdrucks.

Parameter-Liste

Suchmuster

Der Ausdruck nach dem gesucht werden soll als Zeichenkette

Zeichenkette

Die zu zerlegende Zeichenkette

Limit

Falls angegeben, werden maximal Limit Teilzeichenketten zurückgegeben und falls Limit -1 ist, bedeutet das "kein Limit", was für die Angabe von Flags sinnvoll ist.

Flags

Flags kann jede Kombination der folgenden Flags sein (verknüpft mit dem bitweisen | Operator):

PREG_SPLIT_NO_EMPTY
Falls dieses Flag gesetzt ist, werden von preg_split() nur die Teile zurückgegeben, die nicht leer sind.
PREG_SPLIT_DELIM_CAPTURE
Falls dieses Flag gesetzt ist, werden auch die eingeklammerten Ausdrücke des Trennsymbol-Suchmusters erfasst und zurückgegeben.
PREG_SPLIT_OFFSET_CAPTURE

Falls dieses Flag gesetzt ist, wird mit jeder gefundenen Übereinstimmung der dazugehörige Versatz in der Zeichenkette zurückgegeben. Beachten Sie, dass dies die Rückgabewerte in einem Array dahingehend ändert, dass jedes Element ein Array ist, das aus der übereinstimmenden Zeichenkette als Element 0 und deren Stelle in Zeichenkette als Element 1 besteht.

Rückgabewerte

Gibt ein Array zurück, bestehend aus Teilzeichenketten der Zeichenkette , die an den auf das Suchmuster passenden Stellen zerlegt wurde.

ChangeLog

Version Beschreibung
4.3.0 Das Flag PREG_SPLIT_OFFSET_CAPTURE hinzugefügt
4.0.5 Das Flag PREG_SPLIT_DELIM_CAPTURE hinzugefügt
4.0.0 Den Parameter Flags hinzugefügt

Beispiele

Beispiel #1 preg_split() Beispiel: Eine Zeichenkette in ihre Bestandteile zerlegen

<?php
// zerlegt die Zeichenkette an Stellen mit beliebiger Anzahl von
// Kommata oder Leerzeichen, die " ", \r, \t, \n und \f umfassen
$schluesselwoerter preg_split("/[\s,]+/""hypertext language, programming");
?>

Beispiel #2 Eine Zeichenkette in einzelne Zeichen zerlegen

<?php
$str 
'Zeichenkette';
$zeichen preg_split('//'$str, -1PREG_SPLIT_NO_EMPTY);
print_r($zeichen);
?>

Beispiel #3 Eine Zeichenkette in Übereinstimmungen mit dem Suchmuster und deren Versatz zerlegen

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

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

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

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

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

)

Anmerkungen

Tipp

Falls Sie die Leistung regulärer Ausdrücke nicht benötigen, können Sie stattdessen schnellere (wenngleich einfachere) Alternativen wie explode() oder str_split() verwenden.



BBCode> <PCRE Funktionen
Last updated: Fri, 11 Apr 2008
 
add a note add a note User Contributed Notes
preg_split
crispytwo at yahoo dot com
04-Sep-2007 01:29
I was having trouble getting the PREG_SPLIT_DELIM_CAPTURE flag to work because I missed reading the "parenthesized expression" in the documentation :-( 

So the pattern should look like:
/(A)/
not just
/A/
and it works as described/expected.
me
14-Nov-2006 05:56
[Editor's Note: You can use php's wordwrap() to do the exact same thing]

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

BBCode> <PCRE Funktionen
Last updated: Fri, 11 Apr 2008
 
 
show source | credits | stats | sitemap | contact | advertising | mirror sites