Search code examples
phpsubstr

PHP substr by string, not by 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?


Solution

  • 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 ;)