我需要在逗号处将我的字符串输入分割成一个数组。

是否有一种方法将逗号分隔的字符串分解为一个平坦的索引数组?

输入:

9,admin@example.com,8

输出:

['9', 'admin@example', '8']  

当前回答

试着爆炸:

$myString = "9,admin@example.com,8";
$myArray = explode(',', $myString);
print_r($myArray);

输出:

Array
(
    [0] => 9
    [1] => admin@example.com
    [2] => 8
)

其他回答

爆炸在现实生活中有一些非常大的问题:

count(explode(',', null)); // 1 !! 
explode(',', null); // [""] not an empty array, but an array with one empty string!
explode(',', ""); // [""]
explode(',', "1,"); // ["1",""] ending commas are also unsupported, kinda like IE8

这就是为什么我更喜欢preg_split

preg_split('@,@', $string, NULL, PREG_SPLIT_NO_EMPTY)

整个样板文件:

/** @brief wrapper for explode
 * @param string|int|array $val string will explode. '' return []. int return string in array (1 returns ['1']). array return itself. for other types - see $as_is
 * @param bool $as_is false (default): bool/null return []. true: bool/null return itself.
 * @param string $delimiter default ','
 * @return array|mixed
 */
public static function explode($val, $as_is = false, $delimiter = ',')
{
    // using preg_split (instead of explode) because it is the best way to handle ending comma and avoid empty string converted to ['']
    return (is_string($val) || is_int($val)) ?
        preg_split('@' . preg_quote($delimiter, '@') . '@', $val, NULL, PREG_SPLIT_NO_EMPTY)
        :
        ($as_is ? $val : (is_array($val) ? $val : []));
}

如果有人想用for-each将逗号分隔的字符串转换为列表项,那么它将帮助你… 此代码是刀片模板

@php
$data = $post->tags;
$sep_tag= explode(',', $data);
@endphp

@foreach ($sep_tag as $tag)
 <li class="collection-item">{{ $tag}}</li>
 @endforeach 

试着爆炸:

$myString = "9,admin@example.com,8";
$myArray = explode(',', $myString);
print_r($myArray);

输出:

Array
(
    [0] => 9
    [1] => admin@example.com
    [2] => 8
)
//Re-usable function
function stringToArray($stringSeperatedCommas)
{
    return collect(explode(',', $stringSeperatedCommas))->map(function ($string) {
        return trim($string) != null ? trim($string) : null;
    })->filter(function ($string) {
        return trim($string) != null;
    });
}

//Usage
$array = stringToArray('abcd, , dsdsd, dsds');
print($array);

//Result
{ "abcd", "dsdsd", "dsds" }

使用explosion()或preg_split()函数使用指定的分隔符拆分php中的字符串

// Use preg_split() function 
$string = "123,456,78,000";  
$str_arr = preg_split ("/\,/", $string);  
print_r($str_arr); 
  
// use of explode 
$string = "123,46,78,000"; 
$str_arr = explode (",", $string);  
print_r($str_arr);