【问题标题】:How to get a range of arrays如何获取一系列数组
【发布时间】:2016-10-11 11:52:16
【问题描述】:

我有一个代码,我必须使用“*”作为分隔符来分解我的文本。

我有一个模式,总是将数组 [0] 和 [1] 排除在外,其余的需要包含在变量中,但我的问题是我不知道如何动态捕获其余的我必须将它们全部放在里面的数组。

特别是因为我的文本可能有更多的“*”并分解成更多的部分,但我必须将它们放在一起。排除 [0] 和 [1]

$item= explode("*",$c7);

        print_r($item);

//so now that I know which are my [0] and [1] arrays I need to get the rest of them inside of another variable

$variable = ?? //the rest of the $item arrays

【问题讨论】:

  • 能否提供一个具有预期输出的示例字符串?
  • @WiktorStribiżew 是的,我现在就发布它
  • 那么,您需要从a*b*c*d*e 获取c*d*e 吗?那么,Jakub 的答案应该对你有用。
  • @WiktorStribiżew 是的,正是我需要的这种东西。我会尝试使用它,然后我会给出反馈。

标签: php arrays string explode


【解决方案1】:
$str = 'a*b*c*d*e';
$newStr = implode('*', array_slice(explode('*', $str), 2)); // OUTPUT: c*d*e

explode() 用于通过分隔符对字符串进行分块

implode() 用于从块中再次构建字符串

array_slice() 用于选择元素的范围

【讨论】:

  • 我认为应该是$newStr = implode('*', array_slice(explode('*', $str), 2));,但不确定。
  • @WiktorStribiżew,是的,作者之前没有指定结果应该用分隔符分开。
【解决方案2】:

我意识到答案已被接受,但explode 对此有第三个论点,使用end 您可以抓住最后一个非拆分部分:

$str = 'a*b*c*d*e';
$res = end(explode("*", $str, 3));

$res 得到这个值作为结果:

c*d*e

【讨论】:

    【解决方案3】:

    我认为根据您的问题,如果我正确解释它,下面的内容将会很有用。

    使用循环

    $str = "adssa*asdASD*AS*DA*SD*ASD*AS*DAS*D";
    $parts = explode("*", $str);
    
    $newStr = "";
    for ($i = 2; $i < count($parts); ++$i) {
        $newStr .= $parts[$i];
    }
    

    【讨论】:

    • 正确的操作符应该是 .= 否则你会在 php 7 上得到 0(零)
    猜你喜欢
    • 1970-01-01
    • 2015-01-15
    • 1970-01-01
    • 1970-01-01
    • 2020-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-09-24
    相关资源
    最近更新 更多