将字符串拆分为数组并追加上一个值 [英] Split String Into Array and Append Prev Value

查看:64
本文介绍了将字符串拆分为数组并追加上一个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个字符串:

var/log/file.log

var/log/file.log

我最终希望得到一个看起来像这样的数组:

I eventually want to end up with an array looking like this:

Array => [
    '1' => 'var',
    '2' => 'var/log',
    '3' => 'var/log/file.log'
]

我目前有这个:

<?php
    $string = 'var/log/file.log';
    $array = explode('/', $string);
    $output = [
        1 => $array[0],
        2 => $array[0]. '/' .$array[1],
        3 => $array[0]. '/' .$array[1]. '/' .$array[2]
    ];

    echo '<pre>'. print_r($output, 1) .'</pre>';

这真的很违反直觉,我不确定PHP中是否已经内置可以解决此问题的东西.

This feels really counter-intuitive and I'm not sure if there's already something built into PHP that can take care of this.

如何使用附加上一个值来构建数组?

How do I build an array using appending previous value?

推荐答案

此解决方案采用从输入路径开始,然后逐个删除路径的方法,然后在每一步将剩余的输入添加到数组中.然后,作为最后一步,我们反转数组以生成所需的输出.

This solution takes the approach of starting with your input path, and then removing a path one by one, adding the remaining input to an array at each step. Then, we reverse the array as a final step to generate the output you want.

$input = "var/log/file.log";
$array = [];
while (preg_match("/\//i", $input)) {
    array_push($array, $input);
    $input = preg_replace("/\/[^\/]+$/", "", $input);
    echo $input;
}
array_push($array, $input);
$array = array_reverse($array);
print_r($array);

Array
(
    [0] => var
    [1] => var/log
    [2] => var/log/file.log
)

上面对preg_replace的调用去除了输入字符串的最终路径,包括正斜杠.重复此过程,直到只剩下一个最终路径组件.然后,我们将最后一个组件添加到同一数组中.

The above call to preg_replace strips off the final path of the input string, including the forward slash. This is repeated until there is only one final path component left. Then, we add that last component to the same array.

这篇关于将字符串拆分为数组并追加上一个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆