zoukankan      html  css  js  c++  java
  • 字符串转数组(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;
        }
  • 相关阅读:
    一些名词解释
    less那些事儿
    正则表达式检测汉字
    正则匹配括号中内容
    atom中vue高亮支持emmet语法
    正则匹配标签内内容
    联想一体机u盘启动设置
    vuejs时间格式化
    graphicsmagick常用命令
    js中对象的深度复制
  • 原文地址:https://www.cnblogs.com/studyandstudy/p/11725556.html
Copyright © 2011-2022 走看看