Shorten string with a "..." body
Asked Answered
H

4

6

Just like the the iPhone's app names that run to long, the name gets shortened. I really like this method of shorting a name or a string rather then appending a "..." clause to it. Sorry if I am being confusing, I'm having trouble explaining what I am trying to do. So I'll show an example!

This is what I have, to append "..." to a shortened string (In PHP)

<?php
  $string = "This is a test script";

  if (strlen($string) >= 14)
    echo(substr($string), 0, 13). "..."); // This is a test...
  else
    echo($string); // This is a test script
?>

I would like to split up the name or string and keep the first say 10 characters, then insert "..." in the middle and lastly take the ending 5 letters of the string and display them. I was thinking of something along the lines of:

<?php
  $string = "This is a test script";

  if (strlen($string) >= 20)
    echo(substr($string, 0, 10). "..." .substr($string, 15, 20)); //This is a ...script
  else
    echo($string);
?>

But realize that will not work in the regards that there are more then just 5 letters in the end. Any pointers into the write direction would be great, Thanks!

Hartzog answered 23/1, 2010 at 3:56 Comment(1)
For clarification, is it a matter of not wanting to cut off a word in the middle or just being able to get the last 5 characters of the string?Unboned
A
18
if (strlen($string) >= 20) {
    echo substr($string, 0, 10). " ... " . substr($string, -5);
}
else {
    echo $string;
}
Anny answered 23/1, 2010 at 4:4 Comment(1)
I can't believe it was that simple! Thanks!Hartzog
D
2

The third argument of substr() is a length, not an end. Just pass 5 instead.

Also, substr($string, -5).

Darnley answered 23/1, 2010 at 3:59 Comment(1)
This always gets me. Wish there was another substr function in php where it would take two positions as arguments instead of position and length.Educatee
O
1

More generalized solution

function str_short($string, $length, $lastLength = 0, $symbol = '...')
{
    if (strlen($string) > $length) {
        $result = substr($string, 0, $length - $lastLength - strlen($symbol)) . $symbol;
        return $result . ($lastLength ? substr($string, - $lastLength) : '');
    }

    return $string;
}

usage

str_short(string, 20, 5, ' ... ')}}
Obturate answered 14/9, 2020 at 20:21 Comment(0)
I
0

substr cuts words in half. Also if word contains UTF8 characters, it misbehaves. So it would be better to use mb_substr:

$string = mb_substr('word word word word', 0, 10, 'utf8').'...';
Impressure answered 28/4 at 11:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.