dpzp5127 2017-11-10 14:15
浏览 50
已采纳

PHP substr by string,而不是length

I am using this code

substr(trim($val), 0, 2).'/'.substr(trim($val), 0, 4).'/'.trim($val);

to convert

a.b.c.

to

a. / a.b. / a.b.c.

This obviously does not work as soon as I get double digits like a.bb.c., which results in

a. / a.bb / a.bb.c. 

(dot is missing!) instead of

a. / a.bb. / a.bb.c.

Is there a way to extract/trim parts not based on length, but on the dots?

  • 写回答

2条回答 默认 最新

  • dongrong7883 2017-11-10 14:24
    关注

    using explode and a foreach you can make it recursive, like this:

    $val = 'aa.bv.cc.dd';
    $vals = explode('.',$val);
    $result = [];
    foreach($vals as $k => $v) {
        if(trim($v) === '') continue; 
        $result[] = ($k > 0 ? $result[$k-1] : '').$v.'.';
    }
    echo implode(' / ',$result);
    

    in this way you don't need to worry about the amount of letter after each dot and about the amount of segments, and you can handle something like "a.b" or "a.b.c" or "aaa.bbb.ccc.ddd.eeeee" letting the script do all the job for you ;)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 运筹学中在线排序的时间在线排序的在线LPT算法
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 lammps拉伸应力应变曲线分析
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
  • ¥30 python代码,帮调试,帮帮忙吧