Treehouse: Grow your CSS skills. Land your dream job.

Last updated on:

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. 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');
    ?>
    
    • I expected this behavior from your parser so you can ignore the code and open the link ;)

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 in triple backtick fences like this:

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