anthony
anthony

Reputation: 127

Determine if it's end of a string in PHP

Is there a way to determine if it has reached the end of a string or not. Right now I'm using this PHP function

<?php echo substr('some text', 0, 7)?>

To limit the character number to be displayed. Now I would like to add "..." to the text but only if it's not the end of the string.

So when I have a text "Hello!" it would display the whole thing and if I have a text "Determine" it would not only display "Determi" but also adds this "..." like that "Determi...".

I've tried these ellipse and overflow ways but they didn't work for me.

Would something like this described above be possible?

Upvotes: 1

Views: 189

Answers (3)

Tom Lord
Tom Lord

Reputation: 28305

You can achieve this with the built-in function mb_strimwidth:

<?php
echo mb_strimwidth("some text", 0, 7, "...")
// output: "some te..."
?>

Upvotes: 5

Jim Wright
Jim Wright

Reputation: 6058

function trimStr($str, $len = 7) {
  return strlen($str) > $len ? substr($str, 0, $len) . '...' : $str;
}

Upvotes: 0

Alex
Alex

Reputation: 1418

You could do something like this :

<?php echo (strlen($text) > 7 ? (substr($text, 0, 7) . '...') : $text) ?>

If string has more than 7 characters, you echo only the first 7 ones and add ..., otherwise you just echo the text

Upvotes: 3

Related Questions