0

Pop the last x bytes of a string off the string and return it. Any classic way to do it in PHP other than a custom function like this?

function string_pop(&$str, $num) {
    $pop = substr($str, - $num);
    $str = substr($str, 0, strlen($str) - $num);
    return $pop;
}
1

2 Answers 2

1

Maybe something like

list($str, $pop) = str_split($str, strlen($str) - $num);

EDIT: As pointed out by Gergo Erdosi, this code will only work if the $num is less than half of the length of $str. The following would work otherwise.

$arr = str_split($str, strlen($str) - $num);

$pop = array_pop($arr);
$str = implode('', $arr);

But whether or not this is more elegant than you're original function is debatable.

Sign up to request clarification or add additional context in comments.

2 Comments

Run your code with these variables: $str = 'Lorem ipsum dolor sit amet.'; $num = 20;.
Ah yes, my code only works when $num is less than half of the string length
0

Not sure it's the most efficient, but here is a one liner:

list($str, $pop) = preg_split('/(?<=.{'.(strlen($str) - $num).'})/', $str, 2);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.