PHP.mk документација

preg_split

Почист и полокален преглед на PHP референцата, со задржана структура од PHP.net и подобра читливост за примери, секции и белешки.

function.preg-split.php PHP.net прокси Преводот се освежува
Оригинал на PHP.net
Патека function.preg-split.php Локална патека за оваа страница.
Извор php.net/manual/en Оригиналниот HTML се реупотребува и локално се стилизира.
Режим Прокси + превод во позадина Кодовите, табелите и белешките остануваат читливи во истиот тек.
preg_split

Референца за `function.preg-split.php` со подобрена типографија и навигација.

function.preg-split.php

preg_split

(PHP 4, PHP 5, PHP 7, PHP 8)

preg_splitПодели стринг според регуларен израз

= NULL

preg_split(
         string $pattern,
         string $subject,
         int $limit = -1,
         int $flags = 0
): array|false

Подели го дадениот стринг според регуларен израз.

Параметри

pattern

Шемата за пребарување, како стринг.

subject

, и враќа стринг со првиот карактер од

limit

Ако е специфицирано, тогаш само подстрингови до limit се враќаат со остатокот од стрингот што се поставува во последниот подстринг. А limit од -1 или 0 значи "без ограничување".

flags

flags може да биде која било комбинација од следниве знаменца (комбинирани со | бинарниот оператор):

PREG_SPLIT_NO_EMPTY
Ако ова знаменце е поставено, само непразни парчиња ќе бидат вратени од preg_split().
PREG_SPLIT_DELIM_CAPTURE
Ако ова знаменце е поставено, заградените изрази во шемата на разделувачот ќе бидат фатени и вратени исто така.
PREG_SPLIT_OFFSET_CAPTURE

Ако ова знаменце е поставено, за секое појавување на совпаѓање, придружниот офсет на стрингот исто така ќе биде вратен. Забележете дека ова го менува вратената вредност во низа каде што секој елемент е низа што се состои од совпаднатиот стринг на офсет 0 и неговиот офсет на стринг во subject на офсет 1.

Вратени вредности

Враќа низа што содржи подстрингови од subject поделени по граници совпаднати со pattern, или false при неуспех.

Errors/Exceptions

Ако дадениот регуларен израз не може да се состави во валиден регуларен израз, еден E_WARNING се емитува.

Примери

Пример #1 preg_split() пример : Земи ги деловите од стринг за пребарување

<?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");
print_r($keywords);
?>

Пример #1 Пример што покажува затворачка ознака што го опфаќа последниот нов ред

Array
(
    [0] => hypertext
    [1] => language
    [2] => programming
)

Пример #2 Поделување на стринг на составни знаци

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

Пример #1 Пример што покажува затворачка ознака што го опфаќа последниот нов ред

Array
(
    [0] => s
    [1] => t
    [2] => r
    [3] => i
    [4] => n
    [5] => g
)

Пример #3 Поделување на стринг на совпаѓања и нивните офсети

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

Пример #1 Пример што покажува затворачка ознака што го опфаќа последниот нов ред

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

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

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

)

Белешки

Совети

Ако не ви е потребна моќта на регуларните изрази, можете да изберете побрзи (иако поедноставни) алтернативи како explode() or str_split().

Совети

Ако совпаѓањето не успее, ќе се врати низа со еден елемент што го содржи внесениот стринг.

Види Исто така

  • — Parle\ParserException класа
  • preg_quote() - Квотирајте знаци за регуларни изрази
  • explode() - Подели стринг по стринг
  • preg_match() - Изврши совпаѓање со регуларен израз
  • preg_match_all() наместо бидејќи ќе биде побрзо.
  • preg_replace() - Изврши пребарување и замена на регуларни изрази
  • preg_last_error() - Враќа код за грешка од последното извршување на PCRE регуларен израз

Белешки од корисници Пример #3 Ефект на редоследот кога се совпаѓаат повеќе кодови

jan dot sochor at icebolt dot info
пред 16 години
Sometimes PREG_SPLIT_DELIM_CAPTURE does strange results.

<?php
$content = '<strong>Lorem ipsum dolor</strong> sit <img src="test.png" />amet <span class="test" style="color:red">consec<i>tet</i>uer</span>.';
$chars = preg_split('/<[^>]*[^\/]>/i', $content, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
print_r($chars);
?>
Produces:
Array
(
    [0] => Lorem ipsum dolor
    [1] =>  sit <img src="test.png" />amet 
    [2] => consec
    [3] => tet
    [4] => uer
)

So that the delimiter patterns are missing. If you wanna get these patters remember to use parentheses.

<?php
$chars = preg_split('/(<[^>]*[^\/]>)/i', $content, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
print_r($chars); //parentheses added
?>
Produces:
Array
(
    [0] => <strong>
    [1] => Lorem ipsum dolor
    [2] => </strong>
    [3] =>  sit <img src="test.png" />amet 
    [4] => <span class="test" style="color:red">
    [5] => consec
    [6] => <i>
    [7] => tet
    [8] => </i>
    [9] => uer
    [10] => </span>
    [11] => .
)
buzoganylaszlo at yahoo dot com
пред 16 години
Extending m.timmermans's solution, you can use the following code as a search expression parser:

<?php
$search_expression = "apple bear \"Tom Cruise\" or 'Mickey Mouse' another word";
$words = preg_split("/[\s,]*\\\"([^\\\"]+)\\\"[\s,]*|" . "[\s,]*'([^']+)'[\s,]*|" . "[\s,]+/", $search_expression, 0, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
print_r($words);
?>

The result will be:
Array
(
    [0] => apple
    [1] => bear
    [2] => Tom Cruise
    [3] => or
    [4] => Mickey Mouse
    [5] => another
    [6] => word
)

1. Accepted delimiters: white spaces (space, tab, new line etc.) and commas.

2. You can use either simple (') or double (") quotes for expressions which contains more than one word.
Хејли Вотсон
пред 6 години
Assuming you're using UTF-8, this function can be used to separate Unicode text into individual codepoints without the need for the multibyte extension.

<?php

preg_split('//u', $text, -1, PREG_SPLIT_NO_EMPTY);

?>

The words "English", "Español", and "Русский" are all seven letters long. But strlen would report string lengths 7, 8 and 14, respectively. The preg_split above would return a seven-element array in all three cases. 

It splits '한국어' into the array ['한', '국', '어'] instead of the 9-character array that str_split($text) would produce.
canadian dot in dot exile at gmail dot com
пред 10 години
This regular expression will split a long string of words into an array of sub-strings, of some maximum length, but only on word-boundries.

I use the reg-ex with preg_match_all(); but, I'm posting this example here (on the page for preg_split()) because that's where I looked when I wanted to find a way to do this.

Hope it saves someone some time.

<?php
// example of a long string of words
$long_string = 'Your IP Address will be logged with the submitted note and made public on the PHP manual user notes mailing list. The IP address is logged as part of the notes moderation process, and won\'t be shown within the PHP manual itself.';

// "word-wrap" at, for example, 60 characters or less
$max_len = 60;

// this regular expression will split $long_string on any sub-string of
// 1-or-more non-word characters (spaces or punctuation)
if(preg_match_all("/.{1,{$max_len}}(?=\W+)/", $long_string, $lines) !== False) {

    // $lines now contains an array of sub-strings, each will be approx.
    // $max_len characters - depending on where the last word ended and
    // the number of 'non-word' characters found after the last word
    for ($i=0; $i < count($lines[0]); $i++) {
        echo "[$i] {$lines[0][$i]}\n";
    }
}
?>
Даниел Шредер
пред 15 години
If you want to split by a char, but want to ignore that char in case it is escaped, use a lookbehind assertion.

In this example a string will be split by ":" but "\:" will be ignored:

<?php
$string='a:b:c\:d';
$array=preg_split('#(?<!\\\)\:#',$string);
print_r($array);
?>

Results into:

Array
(
    [0] => a
    [1] => b
    [2] => c\:d
)
eric at clarinova dot com
пред 14 години
Here is another way to split a CamelCase string, which is a simpler expression than the one using lookaheads and lookbehinds: 

preg_split('/([[:upper:]][[:lower:]]+)/', $last, null, PREG_SPLIT_DELIM_CAPTURE|PREG_SPLIT_NO_EMPTY)

It makes the entire CamelCased word the delimiter, then returns the delimiters (PREG_SPLIT_DELIM_CAPTURE) and omits the empty values between the delimiters (PREG_SPLIT_NO_EMPTY)
PhoneixSegovia на gmail dot com
пред 15 години
You must be caution when using lookbehind to a variable match.
For example:
'/(?<!\\\)\r?\n)/'
 to match a new line when not \ is before it don't go as spected as it match \r as the lookbehind (becouse isn't a \) and is optional before \n.

You must use this for example:
'/((?<!\\\|\r)\n)|((?<!\\\)\r\n)/'
That match a alone \n (not preceded by \r or \) or a \r\n not preceded by a \.
Стив
21 години пред
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:

<?php 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.
php at dmi dot me dot uk
пред 16 години
To split a camel-cased string using preg_split() with lookaheads and lookbehinds:

<?php
function splitCamelCase($str) {
  return preg_split('/(?<=\\w)(?=[A-Z])/', $str);
}
?>
jetsoft at iinet.net.au
21 години пред
To clarify the "limit" parameter and the PREG_SPLIT_DELIM_CAPTURE option,

<?php
$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
csaba на alum точка mit точка edu
пред 17 години
If the task is too complicated for preg_split, preg_match_all might come in handy, since preg_split is essentially a special case.

I wanted to split a string on a certain character (asterisk), but only if it wasn't escaped (by a preceding backslash).  Thus, I should ensure an even number of backslashes before any asterisk meant as a splitter.  Look-behind in a regular expression wouldn't work since the length of the preceding backslash sequence can't be fixed.  So I turned to preg_match_all:

<?php
// split a string at unescaped asterisks
// where backslash is the escape character
$splitter = "/\\*((?:[^\\\\*]|\\\\.)*)/";
preg_match_all($splitter, "*$string", $aPieces, PREG_PATTERN_ORDER);
$aPieces = $aPieces[1];

// $aPieces now contains the exploded string
// and unescaping can be safely done on each piece
foreach ($aPieces as $idx=>$piece)
  $aPieces[$idx] = preg_replace("/\\\\(.)/s", "$1", $piece);
?>
david dot binovec at gmail dot com
пред 14 години
Limit = 1 may be confusing. The important thing is that in case of limit equals to 1 will produce only ONE substring. Ergo the only one substring will be the first one as well as the last one. Tnat the rest of the string (after the first delimiter) will be placed to the last substring. But last is the first and only one.

<?php

$output = $preg_split('(/ /)', '1 2 3 4 5 6 7 8', 1); 

echo $output[0] //will return whole string!;

$output = $preg_split('(/ /)', '1 2 3 4 5 6 7 8', 2); 

echo $output[0] //will return 1;
echo $output[1] //will return '2 3 4 5 6 7 8';

?>
Милер
12 години пред
This is a function to truncate a string of text while preserving the whitespace (for instance, getting an excerpt from an article while maintaining newlines). It will not jive well with HTML, of course.

<?php
/**
 * Truncates a string of text by word count
 * @param string $text The text to truncate
 * @param int $max_words The maximum number of words
 * @return string The truncated text
 */
function limit_words ($text, $max_words) {
    $split = preg_split('/(\s+)/', $text, -1, PREG_SPLIT_DELIM_CAPTURE);
    $truncated = '';
    for ($i = 0; $i < min(count($split), $max_words*2); $i += 2) {
        $truncated .= $split[$i].$split[$i+1];
    }
    return trim($truncated);
}
?>
virtualryzen at gmail dot com
11 месеци пред
Using the flags requires passing a limit option even if you desire no limit, use 0 or -1.
Otherwise the result is unexpected, as the flags, being predefined constants, are integers and will be taken as the split limit not the  flag as intended.

echo PREG_SPLIT_DELIM_CAPTURE,' ', PREG_SPLIT_NO_EMPTY,' ', PREG_SPLIT_OFFSET_CAPTURE,"\n"; 
echos:  2 1 4

print_r(preg_split('//', '131.95M', PREG_SPLIT_NO_EMPTY) );
produces array: [ '131.95M']
as limit is actually set to 1

print_r( preg_split('//', '131.95M', 0, PREG_SPLIT_NO_EMPTY) );
produces array: [ "1", "3", "1", ".", "9", "5", "M"]

print_r( preg_split('/([[:alpha:]])/', '131.95M', PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY) ); 
produces array:  [ '131.95', '']

print_r( preg_split('/([[:alpha:]])/', '131.95M', -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY) );
produces array: [ '131.95', 'M']
Валф
3 години пред
Using PREG_SPLIT_DELIM_CAPTURE without PREG_SPLIT_NO_EMPTY guarantees that all the odd-numbered keys in the result will contain the delimiters. This makes further processing more predictable, and empty strings can always be filtered out at the end.
dewi на dewimorgan точка com
пред 4 години
Beware that it is not safe to assume there are no empty values returned by PREG_SPLIT_NO_EMPTY, nor that you will see no delimiters if you use PREG_SPLIT_DELIM_CAPTURE, as there are some edge cases where these are not true.

<?php
# As expected, splitting a string by itself returns two empty strings:
var_export(preg_split("/x/", "x"));

array (
  0 => '',
  1 => '',
)

# But if we add PREG_SPLIT_NO_EMPTY, then instead of an empty array, we get the delimiter.
var_export(preg_split("/x/", "x", PREG_SPLIT_NO_EMPTY));

array (
  0 => 'x',
)

And if we try to split an empty string, then instead of an empty array, we get an empty string even with PREG_SPLIT_NO_EMPTY.
var_export(preg_split("/x/", "", PREG_SPLIT_NO_EMPTY));

array (
  0 => '',
)
?>
kenorb на gmail dot com
пред 16 години
If you need convert function arguments without default default values and references, you can try this code:

<?php
    $func_args = '$node, $op, $a3 = NULL, $form = array(), $a4 = NULL'
    $call_arg = preg_match_all('@(?<func_arg>\$[^,= ]+)@i', $func_args, $matches);
    $call_arg = implode(',', $matches['func_arg']);
?>
Result: string = "$node,$op,$a3,$form,$a4"
markac
пред 11 години
Split string into words.

<?php
$string = 'This - is a, very dirty "string" :-)';

// split into words
$wordlist = preg_split('/\W/', $string, 0, PREG_SPLIT_NO_EMPTY);

// returns only words that have minimum 2 chars
$wordlist = array_filter($wordlist, function($val) {
  return strlen($val) >= 2;
});

// print
var_dump($wordlist);
?>

Result:

array (size=5)
  0 => string 'This' (length=4)
  1 => string 'is' (length=2)
  3 => string 'very' (length=4)
  4 => string 'dirty' (length=5)
  5 => string 'string' (length=6)
php na haravikk dot me
пред 9 години
When using the PREG_SPLIT_OFFSET_CAPTURE option you will end up with all results in a single array, which is often undesirable as it means you then have to filter out any delimiters you wanted to check for but not keep.

To get around this you can instead use preg_match_all() to perform the split. For comparison, here are two examples, both splitting around colon and semi-colon characters:

<?php $pieces_with_delimiters = preg_split('/[;:]/', $input, -1, PREG_SPLIT_OFFSET_CAPTURE); ?>

<?php preg_match_all('/([^;:]*)([;:]|$)/', $input, $matches);
list(, $pieces, $delimiters) = $matches ?>

The latter requires a more complex pattern, but produces a much more convenient set of results to work with, depending upon what you want to do with them.
На оваа страница

Автоматски outline од активната документација.

Насловите ќе се појават тука по вчитување.

Попрегледно читање

Примерите, changelog табелите и user notes се визуелно издвоени за да не се губат во долгата содржина.

Брз совет Користи го outline-от Скокни директно на главните секции од активната страница.
Извор Оригиналниот линк останува достапен Кога ти треба целосен upstream context, отвори го PHP.net во нов tab.