当字符串有多个空格时,PHP会将字符串分解为带空格分隔符的数组?

Jas*_*vis 1 php

我下面的PHP代码会将字符串分解为数组.它允许使用多个分隔符来检测数组值应该来自字符串的位置.

在演示中,其中一个分隔符值是一个空格.问题是如果字符串有超过1个连续的空格,它将生成空数组值.

例如key key2 key3 key4,生成数组:

Array
(
    [0] => key
    [1] => key2
    [2] => key3
    [3] => 
    [4] => key4
)
Run Code Online (Sandbox Code Playgroud)

并且所需的输出是:

Array
(
    [0] => key
    [1] => key2
    [2] => key3
    [4] => key4
)
Run Code Online (Sandbox Code Playgroud)

我怎样才能解决这个问题?


/**
 * Explode a string into array with multiple delimiters instead of the default 1 delimeter that explode() allows!
 * @param  array $delimiters - array(',', ' ', '|') would make a string with spaces, |, or commas turn into array
 * @param string $string  text with the delimeter values in it that will be truned into an array
 * @return array - array of items created from the string where each delimiter  in string made a new array key
 */
function multiexplode ($delimiters, $string) {
    $ready = str_replace($delimiters, $delimiters[0], $string);
    $array = explode($delimiters[0], $ready);
    $array = array_map('trim', $array);
    return  $array;
}

$tagsString  = 'PHP JavaScript,WebDev Apollo   jhjhjh';
$tagsArray = multiexplode(array(',',' '), $tagsString);
print_r($tagsArray);
Run Code Online (Sandbox Code Playgroud)

输出数组

Array
(
    [0] => PHP
    [1] => JavaScript
    [2] => WebDev
    [3] => Apollo
    [4] => 
    [5] => 
    [6] => jhjhjh
)
Run Code Online (Sandbox Code Playgroud)

Riz*_*123 11

您可以使用以解决问题并简化代码preg_split().您可以在带有量词字符类中应用包含所有分隔符的正则表达式,并使用分隔符周围的空格.\s*

码:

$array = preg_split("/\s*[" . preg_quote(implode("", $delimiters), "/") . "]+\s*/", $str);
                      ?????????????????????????????????????????????????????????? 
      Consuming any whitespaces                   ?             Consuming any whitespaces 
      around delimiter                            ?             around delimiter
                                   ????????????????
                                   ? []           ? Character class with quantifier
                                   ? implode()    ? Converting array into a string
                                   ? preg_quote() ? Escaping special characters
Run Code Online (Sandbox Code Playgroud)