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;
        }
  • 相关阅读:
    采用get方式提交数据到服务器实例
    android之HttpURLConnection
    Android中的传感器
    有符号类型无符号类型转换
    一些常用位运算示例
    C++ / CLI 调用 C++ /Native 随记
    Linux Shell Demo
    Linux Shell 脚本入门
    Linux 编译 websocket++
    Linux 编写c++程序之openssl
  • 原文地址:https://www.cnblogs.com/studyandstudy/p/11725556.html
Copyright © 2011-2022 走看看