拆分标签上的字符串,删除空结果

Consider the following. I'm splitting a string on {tags}, which are curly braces with anynumber of characters (and/or numbers) in between them:

$string = "Lorem {FOO} ipsum {BAR} dolor {FOO:bar} samet";
$temp   = preg_split('/(\{.*?\})/', $string, -1, PREG_SPLIT_DELIM_CAPTURE);

The resulting array ($temp) is:

Array (
  [0] => Lorem [1] => {FOO} [2] => ipsum [3] => {BAR} 
  [4] => dolor [5] => {FOO:bar} [6] => samet
)

However, if $string ends with a tag, such as:

$string = "Lorem {FOO} ipsum {BAR} dolor {FOO:bar}";

Then the resulting array ($temp) contains an empty element (#6 in this case):

Array (
  [0] => Lorem [1] => {FOO} [2] => ipsum [3] => {BAR} 
  [4] => dolor [5] => {FOO:bar} [6] =>
)

Obviously, this could be afterwards deleted by checking for empty values, but in my mind that is not the most elegant way. Is there an alternative (per regex perhaps?) to not having empty elements in the resulting array to begin with?

Yes use the flag PREG_SPLIT_NO_EMPTY like this:

$string = "Lorem {FOO} ipsum {BAR} dolor {FOO:bar}";
$arr = preg_split('/(\{.*?\})/', $string, 0, 
                  PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY );
print_r($arr);

OUTPUT:

Array
(
    [0] => Lorem 
    [1] => {FOO}
    [2] =>  ipsum 
    [3] => {BAR}
    [4] =>  dolor 
    [5] => {FOO:bar}
)

Your current expression /(\{.*?\})/ could be altered to NOT split, if the split-pattern is the last element of the string. /(\{.*?\})(?!$)/ uses the negative look ahead assertion ((?!…)) to make sure, that your pattern only matches, if it is not followed by EOL ($). But now the Pattern is not recognized any more, leading to the last element before the pattern and the pattern not being separated. What you're left with is:

array(5) {
    "Lorem "
    "{FOO}"
    " ipsum "
    "{BAR}"
    " dolor {FOO:bar}"
}

obviously not what you want either. The first thing that comes to mind is to check if the first and last elements of the split result are empty. if so, remove them. maybe like this:

<?php

$string = "{FOO} ipsum {BAR} dolor {FOO:bar}";
$temp   = preg_split('/(\{.*?\})/', $string, -1, PREG_SPLIT_DELIM_CAPTURE);
$i = 0;
if (isset($temp[$i]) && $temp[$i] === '') {
    array_shift($temp);
}
$i = count($temp) -1;
if (isset($temp[$i]) && $temp[$i] === '') {
    array_pop($temp);
}

var_dump($temp);