Regex PRCE PHP preg_match_all: How do remove empty

2019-08-19 18:15发布

问题:

$text = 'Lorem Ipsum';
$re = '/(?<AA>Any)|(?<BB>Lorem)/ui';
$nMatches = preg_match_all($re, $text, $aMatches);

$aMatches will contain the following:

Array (
    [0] => Array (
            [0] => Lorem
        )

    [AA] => Array (       //  do not include to result matches array
            [0] =>        //  because have not match for this part
        )

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

    [BB] => Array (
            [0] => Lorem
        )

    [2] => Array (
            [0] => Lorem
        )
)

Question: Is it possible to return the array without nodes for named parts that have no matches?

 Array (
        [0] => Array (
                [0] => Lorem
            )

        {there was [AA] && [1], but have not returned because empty} 

        [BB] => Array (
                [0] => Lorem
            )

        [1] => Array (        // changed to 1
                [0] => Lorem
            )
    )

回答1:

Specifically for regex, you can see @Stephan's answer. More generally, when just manipulating arrays, you can use a combination of array_map and array_filter to do that. array_filter without a callback will strip the values that evaluates to false (== false not === false, see empty).

For a single-level array:

$array = array('foo', '', 'bar');
$clean_array = array_filter($array);

For a 2D array:

$clean_array = array_filter(array_map('array_filter', $array));


回答2:

You can achieve something similar by using the branch-reset operator :

/(?|(?<BB>Any)|(?<BB>Lorem))/ui

outputs

  • [0]=> array
    • [0]=>Lorem
  • [BB]=> array
    • [0]=>Lorem
  • [1]=> array
    • [0]=>Lorem

By using this operator the named groups must have the same name.

You test the regexp here.