字符串轉數組(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;
    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM