Truncate Long String Exactly In Middle

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).


$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"



  1. Elvis

    Nice, thanks!

    Here’s my code for links (copy):

            $title = substr_replace($title, '…', $max/2, round(-$max/2));
        $icon = "";
        $link = "$icon $title";
        return $link;
    echo beatufy_url('');
    • Elvis

      I expected this behavior from your parser so you can ignore the code and open the link ;)

  2. RM

    Handy PHP function:

    function truncate_middle($text, $length = 24, $separator = '...')
      if(strlen($text) <= $length)
        return $text;
      $length = ($length - strlen($separator)) / 2;
      return substr_replace($text, $separator, $length, -$length);

Leave a Comment

Posting Code

We highly encourage you to post problematic HTML/CSS/JavaScript over on CodePen and include the link in your post. It's much easier to see, understand, and help with when you do that.

Markdown is supported, so you can write inline code like `<div>this</div>` or multiline blocks of code in triple backtick fences like this:

  function example() {
    element.innerHTML = "<div>code</div>";

We have a pretty good* newsletter.