简体   繁体   English

从第n个字符开始从PHP中剪切字符串

[英]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 我认为与其更改每个实例的硬编码整数值,不如将它从最后一个实例的第4个开始切掉,这样会更好,因为我一直想保留最后4个“斜杠”信息

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 只需对字符串使用explode,如果pattern始终相同,则获取数组的最后一个元素,即可完成工作

$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 下面的函数可以像第n次出现的substr一样工作

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 在第4次出现“-”后进行substr以获得“您正在做”,将上述函数调用为

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

it will result as 它会导致

you-doing

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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