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.
If it isn't found, it should preferably return false.
I have the feeling I'm overlooking some very obvious PHP functions here, but I can't seem to think of them right now.
For example:
$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.
This case calls for strncmp:
How about regular expressions?
Put more simply than the other examples:
DEMO
Alternate using strncmp, too: DEMO
But what about this?
You likely want to call
realpath()
on$path
first, so that it is fully simplified, before usingsome_function()
.Not sure if there's a built-in function for this.
For long
$str1
and short$str2
, I think this is going to be faster than usingstrpos
.If you're using this for paths, you might want to do some checking if the slashes are at the right place.