简体   繁体   中英

Cut string in PHP at 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

Many thanks

EDIT - final code solution

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

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

This function below can work like a substr start from nth occurrence

function substr_after_nth($str, $needle, $key) 
{
    $array = explode($needle, $str);
    $temp = array();
    for ($i = $key; $i < count($array); $i++) {
        $temp[] = $array[$i];
    }
    return implode($needle, $temp);
}

Example

$str = "hello-world-how-are-you-doing";

substr after 4th occurrence of "-" to get "you-doing" call the function above as

echo substr_after_nth($str, "-", 4);

it will result as

you-doing

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM