开发者

reading and removing a substring in the most efficient way possible, like array_pop() but for sub strings

I have a string that could look like any of the following. In other words, it may have "in the morning" or "in the evening" but sometimes, it may not have anything.

"bla bla in the morning" or 
"bla bla bla in the evening" or 
"bla bla bla"

Does php have a function to both isolate and remove that sub string at the same time? something like $last_in_array = array_pop($arr); that both saves the last element into $last_in_array AND removes it from the array at the same time. Anything like that for strings for the scenario I'm explaining. If not, what's a really effici开发者_开发技巧ent way to do this?


function string_pop(&$haystack, $needle) {
    if (strpos($haystack, $needle) !== false) {
        $haystack = str_replace($needle, "", $haystack);
        return $needle;
    }
    return false;
}

$string = "bla bla in the morning";
$return = string_pop($string, " in the morning");

var_dump($string);
var_dump($return);

Output:

$string: string(7) "bla bla"
$return: string(15) " in the morning"
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜