How can I split a delimited string into an array in PHP?

前端 未结 10 1923
失恋的感觉
失恋的感觉 2020-11-21 11:11

I need to split my string input into an array at the commas.

How can I go about accomplishing this?

Input:

9,admin@example.com,8
10条回答
  •  耶瑟儿~
    2020-11-21 11:55

    explode has some very big problems in real life usage:

    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
    

    this is why i prefer preg_split

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

    the entire boilerplate:

    /** @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 : []));
    }
    

提交回复
热议问题