Is there some better way to do the below?
(without having the possibility of a fatal error)
function remove_before($needle,$haystack){
return substr(strstr($haystack,$needle),strlen($needle));
}
like strstr($haystack,$needle) but without the needle in the returned string,
and I might as well ask if this can be improved too…
function remove_after($needle,$haystack){
return substr($haystack, 0, strrpos($haystack, $needle));
}
note that remove after strips the string after the last occurrence of needle, and remove before strips the string before the first occurrence of needle.
edit:
example:
$needle = '@@';
$haystack = 'one@@two@@three';
remove_after($needle,$haystack);//returns one@@two
remove_before($needle,$haystack)://returns two@@three
edit:
I will leave it here for other people to reference.
There are two things about the functions as written:
They have no error handling. For example, in remove_before: needle not in haystack causes it to pass
falseas the first argument tosubstr. I haven’t tried it, but I’m pretty sure this will cause a runtime error.In
remove_before,strposis faster and less memory intensive thanstrstr.Therefore:
and likewise,
remove_after: