在php中如何使用索引将字符串分解为数组?
我有一个PHP字符串,由如下字符分隔:在php中如何使用索引将字符串分解为数组?,php,Php,我有一个PHP字符串,由如下字符分隔: $str = "var1,'Hello'|var2,'World'|"; $sub_str = explode("|", $str); 我使用explode函数在数组中拆分字符串,如下所示: $str = "var1,'Hello'|var2,'World'|"; $sub_str = explode("|", $str); 它返回: $substr[0] = "var1,'hello'"; $substr[1] = "var2,'world'";
$str = "var1,'Hello'|var2,'World'|";
$sub_str = explode("|", $str);
我使用explode函数在数组中拆分字符串,如下所示:
$str = "var1,'Hello'|var2,'World'|";
$sub_str = explode("|", $str);
它返回:
$substr[0] = "var1,'hello'";
$substr[1] = "var2,'world'";
在这种情况下,有没有办法在数组中分解$substr
:
$substr
的第一部分是数组索引,$substr
的第二部分是变量
例如:
$new_substr = array();
$new_substr["var1"] = 'hello';
$new_substr["var2"] = 'world';
当我调用我的$new\u substr
时,它只返回结果
例如:
echo $new_substr["var1"];
然后返回:hello您可以使用
explode()
,str\u replace()
函数来完成
步骤很简单:
1) 使用|
将字符串分成两段,这将形成一个包含两个元素的数组
2) 在拆分的数组上循环
3) 如不需要,替换单引号
4) 将foreach当前元素替换为逗号(,)
5) 现在,我们将键和值分开
6) 将其附加到数组中
7) 享受
代码:
请尝试以下代码:
$str = "var1,'Hello'|var2,'World'|";
preg_match_all('/(?:^|\|)([^,]+),([^\|]+(?=\||$))/', $str, $matches);
$new_substr = array_combine($matches[1], $matches[2]);
print_r($new_substr);
您可以使用提取键和值,然后使用将它们放在一起:
Array (
[var1] => 'Hello'
[var2] => 'World'
)
输出:
$str = "var1,'Hello'|var2,'World'|";
$sub_str = explode("|", $str);
$new_str = array();
foreach ( $sub_str as $row ) {
$test_str = explode( ',', $row );
if ( 2 == count( $test_str ) ) {
$new_str[$test_str[0]] = str_replace("'", "", $test_str[1] );
}
}
print $new_str['var1'] . ' ' . $new_str['var2'];
请尝试以下代码:
$str = "var1,'Hello'|var2,'World'|";
preg_match_all('/(?:^|\|)([^,]+),([^\|]+(?=\||$))/', $str, $matches);
$new_substr = array_combine($matches[1], $matches[2]);
print_r($new_substr);
只需在循环中用逗号分解$sub_str
,并替换值中的单引号即可提供预期结果