Tutorial Truncate Long String Exactly In Middle

by in , 0

This will truncate a longer string to a smaller string of specified length (e.g. the "25" value in the code below) while replacing the middle portion with a separator exactly in the middle. Useful when you need to truncate a string but still show the beginning (e.g. for sorting and because it is most recognizable) and also show the end (perhaps to show a file name).

<?php

$longString = 'abcdefghijklmnopqrstuvwxyz0123456789z.jpg';
$separator = '/.../';
$separatorlength = strlen($separator) ;
$maxlength = 25 - $separatorlength;
$start = $maxlength / 2 ;
$trunc =  strlen($longString) - $maxlength;

echo substr_replace($longString, $separator, $start, $trunc);

//prints "abcdefghij/.../56789z.jpg"

?>

Leave a Reply