仅在某个基本字符串之后获取字符串最后一部分的有效方法 [英] Efficient way to get last part of string only after a certain base string

查看:22
本文介绍了仅在某个基本字符串之后获取字符串最后一部分的有效方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在某个针出现后获取字符串部分的有效方法是什么,如果该针位于大海捞针的开头.与 strstr() 类似,但排除针,并且仅当在字符串的开头找到时.

What is an efficient way to get the part of a string after the occurrence of a certain needle, only if that needle is at the start of the haystack. Similar to strstr(), but excluding the needle, and only when found at the beginning of the string.

如果没有找到,最好返回false.

If it isn't found, it should preferably return false.

我感觉我在这里忽略了一些非常明显的 PHP 函数,但我现在似乎想不起来.

I have the feeling I'm overlooking some very obvious PHP functions here, but I can't seem to think of them right now.

例如:

$basePath = '/some/dir/';

$result = some_function( '/some/dir/this/is/the/relative/part', $basePath );
/*
should return:
this/is/the/relative/part
*/

$result = some_function( '/fake/dir/this/is/the/relative/part', $basePath );
$result = some_function( '/pre/some/dir/this/is/the/relative/part', $basePath );
/*
last example has '/some/dir/' in it, but not at start.
should both preferably return:
false
*/

我将把它用于一个文件系统服务,它应该作为一个沙箱,并且应该能够给出和接收相对于基础沙箱目录的路径.

I'll be using this for a filesystem service that should act as a sandbox, and should be able to give out and take in paths, relative to the base sand box directory.

推荐答案

比其他例子更简单:

function some_function($path,$base){
  $baselen = strlen($base);
  if (strpos($path,$base) === 0 && strlen($path)>$baselen)
    return substr($path,$baselen);
  return false;
}

演示

也可以使用 strncmp:演示

Alternate using strncmp, too: DEMO

这篇关于仅在某个基本字符串之后获取字符串最后一部分的有效方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆