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

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

?>

Comments

  1. User Avatar
    Elvis

    Nice, thanks!

    Here’s my code for links (copy):

    
     $max)
            $title = substr_replace($title, '…', $max/2, round(-$max/2));
        $icon = "";
        $link = "$icon $title";
        return $link;
    }
    echo beatufy_url('http://en.wikipedia.org/wiki/World_Bank_Governance_Surveys');
    ?>
    
    • User Avatar
      Elvis

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

  2. User Avatar
    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);
    }
    

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.

Submit a Comment

icon-closeicon-emailicon-linkicon-menuicon-searchicon-tag