Search code examples
phpstringpathsubstring

Isolate substring at end of string starting from the nth-from-end occurrence of character


I have a string which can be written in a number of different ways, it will always follow the same pattern but the length of it can differ.

this/is/the/path/to/my/fileA.php
this/could/also/be/the/path/to/my/fileB.php
another/example/of/a/long/address/which/is/a/path/to/my/fileC.php

What I am trying to do is cut the string so that I am left with

path/to/my/file.php

I have some code which I got from this page and modified it to the following

$max = strlen($full_path);
$n = 0;
for($j=0;$j<$max;$j++){
    if($full_path[$j]=='/'){
        $n++;
        if($n>=3){
            break 1;
        }
    }
}
$path = substr($full_path,$j+1,$max);

Which basically cuts it at the 3rd instance of the '/' character, and gives me what is left. This was fine when I was working in one environment, but when I migrated it to a different server, the path would be longer, and so the cut would give me too long an address. I thought that rather than changing the hard coded integer value for each instance, it would work better if I had it cut the string at the 4th from last instance, as I always want to keep the last 4 'slashes' of information.

EDIT - final code solution

$exploded_name = explode('/', $full_path);
$exploded_trimmed = array_slice($exploded_name, -4);
$imploded_name = implode('/', $exploded_trimmed);

Solution

  • just use explode with your string and if pattern is always the same then get last element of the array and your work is done

    $pizza  = "piece1/piece2/piece3/piece4/piece5/piece6";
    $pieces = explode("/", $pizza);
    echo $pieces[0]; // piece1
    echo $pieces[1]; // piece2
    

    Then reverse your array get first four elements of array and combine them using "implode" to get desired string