开发者

remove_before()

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,$hayst开发者_开发百科ack)://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 false as the first argument to substr. I haven't tried it, but I'm pretty sure this will cause a runtime error.

In remove_before, strpos is faster and less memory intensive than strstr.

Therefore:

function remove_before($needle, $haystack){
    $pos = strpos($haystack, $needle);
    // No needle found
    if (false === $pos)
        return $haystack;
    return substr($haystack, $pos + strlen($needle));
}

and likewise, remove_after:

function remove_after($needle, $haystack){
    $pos = strrpos($haystack, $needle);
    // No needle found
    if (false === $pos)
        return $haystack;
    return substr($haystack, 0, $pos);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜