duandan9680 2014-07-16 16:23
浏览 23
已采纳

我怎么能总是从爆炸中返回最后一系列数字

I have a line of code like

$qs = explode('&',$_SERVER['QUERY_STRING']);
$pid = explode('=',$qs[1]);

this will return something such as array(2) { [0]=> string(5) "cPath" [1]=> string(14) "70_229_242_240" }

I then have

$cat_ID = explode('_',$pid[1]);

which returns array(4) { [0]=> string(2) "70" [1]=> string(3) "229" [2]=> string(3) "242" [3]=> string(3) "240" }

Using

print_r($cat_ID[3]);

i can get the final value of 240.

However, this only works in instances where the original string is made up of four numbers separated by underscores. In some circumstances i may have a string of three, two or even one number.

Is there a simple way to make it always fetch the last number in the string without having to code a bunch of if statements to cover situations where $cat_ID[3] or $cat_ID[2] would be empty/non existant?

I suspect the

$pid = explode('=',$qs[1]);

can be changed to take the numbers following the last underscore, but i break it every time i try.

  • 写回答

1条回答 默认 最新

  • douliang2935 2014-07-16 16:25
    关注

    Is there a simple way to make it always fetch the last number in the string without having to code a bunch of if statements to cover situations where $cat_ID[3] or $cat_ID[2] would be empty/non existant?

    Sure;

    • Explode, like you've done
    • Count the number of elements, minus 1 (as it will start at index 0)

      <?php
      $cat_ID = explode('_',$pid[1]);    
      $intLastNumber = $cat_ID[count($cat_ID)-1]
      

    Some example code;

    <?php
    $str = "1_2_3_4_5";
    $arrNumbers = explode("_", $str);
    
    echo $arrNumbers[count($arrNumbers)-1]; //Should be 5.
    

    http://codepad.org/HEUSmLkg

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序
  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作