【问题标题】:How to double split string in PHP?如何在PHP中双重分割字符串?
【发布时间】:2020-05-31 12:19:47
【问题描述】:

我有一个问题,即使在 Google 中搜索几个小时也无法解决。

我有字符串例如:

$string = "___username1,password1___username2,password2";

我需要从“___”中拆分字符串,然后将结果保存到变量中,然后从每个“,”中再次拆分它,所以结果应该是:

从第一个拆分结果开始:

$s[0] = username1,password1
$s[1] = username2,passwrod2

从第二次拆分开始,我需要得到如下结果:

username1
password1
username2
password2

我试过了:

$s0 = explode("___",$string);
$s1 = explode(",",$s0);

错误:

警告:explode() 期望参数 2 是字符串,给定数组

你能帮帮我吗?

【问题讨论】:

  • 你尝试过显而易见的并循环遍历数组吗?

标签: php split


【解决方案1】:

使用___ 作为分隔符的explode() 几乎就在那里。然后,您可以使用 array_map() 两件事来处理结果,回调为 str_getcsv,因为每个部分都是逗号分隔的列表。

由于字符串以分隔符开头,因此使用array_shift() 删除开头的空白条目...

$final = array_map("str_getcsv", explode("___", $string));
array_shift($final);
print_r($final);

给...

Array
(
    [0] => Array
        (
            [0] => username1
            [1] => password1
        )

    [1] => Array
        (
            [0] => username2
            [1] => password2
        )

)

【讨论】:

    【解决方案2】:

    我不确定最佳做法,但也许我们可以将“_”替换为其他内容。

        $s[0] = str_replace("___","*+*",$string);
        $s[0] = explode("*+*",$string);
    

    【讨论】:

    • 你为什么要替换模式?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多