user1876234
user1876234

Reputation: 857

How to add ... after end of string when using 'substr' in php?

I have text, for example:

$str = 'Hi there bla bla';

I used substr function for $str

substr($str, 0 , 20);

I got full text, but if I have longer text, lets say:

$str = "Hi there bla bla Hi there bla bla Hi there bla bla";
$substred = substr($str, 20, 21);

I thought I can use

if ($substred) { echo "..."; };

But it's not working .. ?

Upvotes: 0

Views: 5366

Answers (6)

Pierre
Pierre

Reputation: 675

If you want it in an inline form using ternary logic

You can do it as follow:

$string = "Hey, Hello World"
strlen($string) < 10 ? $string : substr($string, 0, 10) . '...';

output: Hey, Hello...

Upvotes: 0

Jason
Jason

Reputation: 15931

This doesn't answer the question directly, but may be useful if the string is meant to be displayed via HTML. It can be done in CSS by using the style property text-overflow with a value of ellipsis.

$str

Upvotes: 0

Lemur
Lemur

Reputation: 2665

  1. Always chceck, if your string you want to strip has this 20 chars to prevent disasters
  2. If you do check, you may easily add condition to add ... to your string

Code:

if (strlen($string) > 20) {
   $string = substr($string, 0, 20) . "..."; }

Upvotes: 4

Keith A
Keith A

Reputation: 801

im assuming you want to echo a text but only part of it if it's too long and add "...". this might work..

if (strlen("$txt")> 20){
   echo substr($txt,0,20)."...";
}

Upvotes: 0

Kevin Pei
Kevin Pei

Reputation: 5872

Is this what you're looking for? You should probably count it first, then echo the result. http://codepad.org/OFo6MG6P

<?php
$str = 'Hi there bla bla';
echo 'Original: "'.$str.'", long one: "';
substr($str, 0 , 20);
$str = "Hi there bla bla Hi there bla bla Hi there bla bla";
$substred = substr($str, 20, 21);
if (strlen($str) > 20) { echo $substred."...\""; };
?>

Upvotes: 0

kabuto178
kabuto178

Reputation: 3167

You need to echo out the full statement with dots like this

$str = "Hi there bla bla Hi there bla bla Hi there bla bla";
$sentence = substr($str, 0, 21);
echo $sentence."....";

Upvotes: 0

Related Questions