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"

Deploy a static site in one minute
Build and deploy a CMS-enabled site with Gatsby in just a few clicks. It's free.


  1. User Avatar

    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('');
    • User Avatar

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

  2. User Avatar

    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!

You may write comments in Markdown. This makes code easy to post, as you can write inline code like `<div>this</div>` or multiline blocks of code in triple backtick fences (```) with double new lines before and after.

Code of Conduct

Absolutely anyone is welcome to submit a comment here. But not all comments will be posted. Think of it like writing a letter to the editor. All submitted comments will be read, but not all published. Published comments will be on-topic, helpful, and further the discussion or debate.

Want to tell us something privately?

Feel free to use our contact form. That's a great place to let us know about typos or anything off-topic.