Php preg split no empty

preg_split

Возвращает массив, состоящий из подстрок заданной строки 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() пример: Получение подстрок из заданного текста
// разбиваем строку по произвольному числу запятых и пробельных символов, // которые включают в себя " ", \r, \t, \n и \f $keywords = preg_split("/[\s,]+/", "hypertext language, programming");
Пример 2. Разбиваем строку на составляющие символы
$str = 'string'; $chars = preg_split('//', $str, -1, PREG_SPLIT_NO_EMPTY); print_r($chars);
Пример 3. Разбиваем строку с указанием смещения для каждой из найденных подстрок
$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.

Источник

preg_split

If specified, then only substrings up to limit are returned with the rest of the string being placed in the last substring. A limit of -1 or 0 means «no limit».

flags can be any combination of the following flags (combined with the | 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. 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 .

Return Values

Returns an array containing substrings of subject split along boundaries matched by pattern , or false on failure.

Errors/Exceptions

If the regex pattern passed does not compile to a valid regex, an E_WARNING is emitted.

Examples

Example #1 preg_split() example : Get the parts of a search string

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

Читайте также:  Установить новую версию java jre

The above example will output:

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

Example #2 Splitting a string into component characters

$str = ‘string’ ;
$chars = preg_split ( ‘//’ , $str , — 1 , PREG_SPLIT_NO_EMPTY );
print_r ( $chars );
?>

The above example will output:

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

Example #3 Splitting a string into matches and their offsets

$str = ‘hypertext language programming’ ;
$chars = preg_split ( ‘/ /’ , $str , — 1 , PREG_SPLIT_OFFSET_CAPTURE );
print_r ( $chars );
?>

The above example will output:

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

Notes

If you don’t need the power of regular expressions, you can choose faster (albeit simpler) alternatives like explode() or str_split() .

If matching fails, an array with a single element containing the input string will be returned.

See Also

  • PCRE Patterns
  • preg_quote() — Quote regular expression characters
  • implode() — Join array elements with a string
  • preg_match() — Perform a regular expression match
  • preg_match_all() — Perform a global regular expression match
  • preg_replace() — Perform a regular expression search and replace
  • preg_last_error() — Returns the error code of the last PCRE regex execution

User Contributed Notes 18 notes

Sometimes PREG_SPLIT_DELIM_CAPTURE does strange results.

$content = ‘Lorem ipsum dolor sit amet consectetuer.’ ;
$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 amet
[2] => consec
[3] => tet
[4] => uer
)

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

$chars = preg_split ( ‘/(<[^>]*[^\/]>)/i’ , $content , — 1 , PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE );
print_r ( $chars ); //parentheses added
?>
Produces:
Array
(
[0] =>
[1] => Lorem ipsum dolor
[2] =>

[3] => sit amet
[4] =>
[5] => consec
[6] =>
[7] => tet
[8] =>

[9] => uer
[10] =>

[11] => .
)

Extending m.timmermans’s solution, you can use the following code as a search expression parser:

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

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.

Читайте также:  Log javascript errors to file

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.

// 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 ( «/. >(?=\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» ;
>
>
?>

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.

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.

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)

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:

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:

So you actually get 7 array items not 4

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:

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.

You must be caution when using lookbehind to a variable match.
For example:
‘/(? 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.

Читайте также:  Javascript возврат значения функции

You must use this for example:
‘/((?That match a alone \n (not preceded by \r or \) or a \r\n not preceded by a \.

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.

# As expected, splitting a string by itself returns two empty strings:
var_export ( preg_split ( «/x/» , «x» ));

# 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 ));

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

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.

/**
* 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 );
>
?>

To split a camel-cased string using preg_split() with lookaheads and lookbehinds:

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:

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

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.

$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’;

Источник

Оцените статью