字符串转数组,php版

思路:

1.判断当前传来的值是否为数组

2.若不是现将传来的值转换为字符串类型

3.判断当前值是否为空

4.若不为空,采用正则进行匹配,如下图

preg_match('/^{.*?}$/', $string) || preg_match('/^\[.*?]$/', $string) || preg_match('/^a:.*?(})$/', $string)

5.若正则无法匹配,则采用查找首次字符串出现的位置进行拆分分割

strpos($string, $delimiter) >= 1

具体代码示例如下

    /**
     * 字符串、数组转换为格式化的数组
     * @param string|array $data      原始字符串,可以为数组、 json字符串、 序列化字符串
     * @param string       $delimiter 字符串分隔符,默认为英文逗号
     * @return array
     */
    function cm_unserialize($data, string $delimiter = ','): array
    {

        // 数组原样返回
        if (is_array($data)) {
            return $data;
        }
        // 字符串处理
        $string = (string)$data;
        if (empty($string)) {
            $result = [];
        } else if (preg_match('/^{.*?}$/', $string) || preg_match('/^\[.*?]$/', $string)) {
            $result = json_decode($string, true);
        } else if (preg_match('/^a:.*?(})$/', $string)) {
            $result = unserialize($string, null);
        } else if (strpos($string, $delimiter) >= 1) {
            $result = explode($delimiter, $string);
        } else {
            $result = [];
        }

        if (!is_array($result) || count($result) < 1) {
            return [];
        }
        return $result;
    }