I've just taken a look at the post by ntoniazzi and I have a very small correction to make.
In the second if statement, it should be a triple equals, so:
<?php if ($length === null) ?>
It requires the triple equals, for the case of pure insertion, where $length = 0, the double equals, will catch this, causing the string to be cut short. I hope this helps someone.