I was reviewing old codes when I found a function that "truncates" a given string after X characters: / p>
This function, unlike a substr () simple, does not leave the developer in embarrassing situations like this:
$str = 'Então, Chapeuzinho Vermelho decide tomar no cantinho, bem escondida, uma lata de leite condensado.';
var_dump( substr( $str, 45 ) . '...' );
That would result in:
So, Little Red Riding Hood decides to take on the ...
It's annoying ...: p
With this enhanced function, a statement like this:
var_dump( truncate( $str, 45, 'after' ) );
It would result in:
So Little Red Riding Hood decides to take it in the corner, ...
Much better: D
However, I found two minor issues with the third scenario covered by the function, which adds the ellipsis in the middle of the string, like this:
So, Little Red Riding Hood ... well hidden, a can of condensed milk.
The first of these is that, as seen in the above example, the ellipsis (or other / substring character set) is not added near the middle of the string as it should.
The second problem is only noticeable with some specific, often short, strings like this:
$str = 'Eu coloquei meu cabo de enxada no seu curral';
var_dump( truncate( $str, 35, 'center' ) );
This would produce:
I put my cable ... your corral
That is, the n letter of in your has been unduly suppressed.
I even managed to solve this problem by subtracting 1 (one) from strlen( $append )
of $ end .
But while this solves for small phrases, it corrupts for long phrases, causing the example of Little Red Riding Hood to result in:
So, Little Red Riding Hood ... ## cantinho, well hidden, a can of condensed milk.
That is, with an extra space after the string inserted (before cantinho ) in what would be the almost middle of the string (replaces with hashes to stay visible).
It's a silly problem in offset , but I could not solve it correctly.
For a time, a workaround was to replace any double spaces in the string before returning, but if possible fix instead of remedy, the better.
Any ideas?