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

  • Use Markdown, and it will escape the code for you, like `<div class="cool">`.
  • Use triple-backticks for blocks of code.
    ``` 
    <div>
      <h1>multi-line block of code</h1>
      <span>be cool yo.</span>
    </div>
    ```
  • Otherwise, escape your code, like <code>&lt;div class="cool"&gt;</code>. Markdown is just easier though.

Current ye@r *

*May or may not contain any actual "CSS" or "Tricks".