如何在php中将字符串转换为数组

PHP 中如何将字符串转换为数组?我有一个像这样的字符串:


$str = "php/127/typescript/12/jquery/120/angular/50";

输出:


Array (

    [php]=> 127

    [typescript]=> 12

    [jquery]=> 120

    [angular]=> 50

)


GCT1015
浏览 123回答 3
3回答

千万里不及你

您可以使用preg_match_all(正则表达式)和array_combine:使用正则表达式:$str = "php/127/typescript/12/jquery/120/angular/50";#match stringpreg_match_all("/([^\/]*?)\/(\d+)/", $str, $match);#then combine match[1] and match[2] $result = array_combine($match[1], $match[2]);print_r($result);演示(带步骤): https: //3v4l.org/blZhU

郎朗坤

一种方法可能是preg_match_all分别从路径中提取键和值。然后,使用array_combine构建哈希图:$str = "php/127/typescript/12/jquery/120/angular/50";preg_match_all("/[^\W\d\/]+/", $str, $keys);preg_match_all("/\d+/", $str, $vals);$mapped = array_combine($keys[0], $vals[0]);print_r($mapped[0]);这打印:Array(    [0] => php    [1] => typescript    [2] => jquery    [3] => angular)

元芳怎么了

您可以explode()与for()Loop 一起使用,如下所示:-<?php&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; $str = 'php/127/typescript/12/jquery/120/angular/50';&nbsp; &nbsp; $list = explode('/', $str);&nbsp; &nbsp; $list_count&nbsp; = count($list);&nbsp; &nbsp; $result = array();&nbsp; &nbsp; for ($i=0 ; $i<$list_count; $i+=2) {&nbsp; &nbsp; &nbsp; &nbsp; $result[ $list[$i] ] = $list[$i+1];&nbsp; &nbsp; }&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; print_r($result);&nbsp; &nbsp; ?>输出:-&nbsp;Array&nbsp; &nbsp; (&nbsp; &nbsp; &nbsp; &nbsp; [php] => 127&nbsp; &nbsp; &nbsp; &nbsp; [typescript] => 12&nbsp; &nbsp; &nbsp; &nbsp; [jquery] => 120&nbsp; &nbsp; &nbsp; &nbsp; [angular] => 50&nbsp; &nbsp; )&nbsp; &nbsp;&nbsp;此处演示:-&nbsp;https://3v4l.org/8PQhd
打开App,查看更多内容
随时随地看视频慕课网APP