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条)

报告相同问题?