字符串转数组(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;
} 相关推荐
卖口粥湛蓝的天空 2020-09-15
stulen 2020-09-15
Lzs 2020-10-23
聚合室 2020-11-16
零 2020-09-18
Justhavefun 2020-10-22
ChaITSimpleLove 2020-10-06
周游列国之仕子 2020-09-15
afanti 2020-09-16
88234852 2020-09-15
YClimb 2020-09-15
风雨断肠人 2020-09-04
pythonxuexi 2020-09-06
abfdada 2020-08-26
梦的天空 2020-08-25