在Php中根据特殊字符将字符串拆分为数组

4

我有一个字符串:

xyz.com?username="test"&pwd="test"@score="score"#key="1234"

输出格式:

array (
    [0] => username="test"
    [1] => pwd="test"
    [2] => score="score"
    [3] => key="1234"
)

你尝试过什么吗? - Rizier123
preg_split("/?|&|@|#/", $string) - splash58
2个回答

5
这个方法适用于你:
只需使用preg_split(),并在其中使用包含所有分隔符的字符类。最后使用array_shift()来删除第一个元素即可。
<?php

    $str = 'xyz.com?username="test"&pwd="test"@score="score"#key="1234"';

    $arr = preg_split("/[?&@#]/", $str);
    array_shift($arr);

    print_r($arr);

?>

输出:

Array
(
    [0] => username="test"
    [1] => pwd="test"
    [2] => score="score"
    [3] => key="1234"
)

1
你可以使用包括所有这些分隔特殊字符的正则表达式模式与 preg_split 函数。然后删除数组的第一个值并重置键:
$s = 'xyz.com?username="test"&pwd="test"@score="score"#key="1234"';
$a = preg_split('/[?&@#]/',$s);
unset($a[0]);
$a = array_values($a);

print_r($a);

输出:

Array ( 
[0] => username="test" 
[1] => pwd="test" 
[2] => score="score" 
[3] => key="1234" 
) 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接