【问题标题】:Get remaining split string on PHP after explode爆炸后在PHP上获取剩余的拆分字符串
【发布时间】:2014-04-02 09:00:27
【问题描述】:

我希望能够在爆炸后得到剩余的字符串。

$string = "First Middle Last";
$d = explode(" ", $string);
print_r($d);

Outputs:
$d = array
(
  [0] => First
  [1] => Middle
  [2] => Last
)

$first = $d[0]; // First
$last = $d[1] // Middle

如何获得最后一个和剩余的分解值?

我希望能够做到:

$last = $d[last?] // Middle Last

我不想做

$last = $d[1].$d[2] // Middle Last

【问题讨论】:

    标签: php arrays string function explode


    【解决方案1】:

    您可以使用array_slice。这将无限期地适用于任何字符串。

    <?php
    $string = "First Middle Last Next Over";
    echo implode(' ',array_slice(explode(" ", $string),1));
    

    OUTPUT :

    Middle Last Next Over
    

    【讨论】:

      【解决方案2】:

      您可能应该使用explode 的第三个(可选)参数:

      list ($first, $last) = explode(" ", $string, 2);
      

      也就是说,空格分割将适用于很多人名,但如果从全局角度来看,也会在相当大的百分比上失败。将其作为针对特定问题的实用解决方案没有错,只是不要期望它总是能正常工作。

      【讨论】:

      • 这是最简单的修复方法。感谢您在爆炸时提供的额外参数。成功了!
      【解决方案3】:
      $string = "First Middle Last";
      
      preg_match_all("/\s(.*)/", $string , $output_array);
      
      echo $output_array[1][0];
      
      Output // Middle Last
      

      或者干脆

      preg_match("/\s(.*)/", $string , $output_array);
      
      echo $output_array[1];
      

      【讨论】:

        【解决方案4】:

        试试这个。

        $string = "First Middle Last";
        list($d1,$d2,$d3) = explode(" ", $string);
        print_r($d1);
        print_r($d2);
        print_r($d3);
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-12-10
          • 2011-07-20
          • 2013-09-09
          相关资源
          最近更新 更多