0

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 .. ?

G.Ashok Kumar
  • 1,649
  • 2
  • 13
  • 25
user1876234
  • 857
  • 2
  • 14
  • 28

6 Answers6

4
  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) . "..."; }
Lemur
  • 2,659
  • 4
  • 26
  • 41
  • What disasters are you talking about? – nickb Mar 31 '13 at 18:06
  • In some cases (from my experience) the code didn't work when string was shorter than the length I wanted to strip - (something similar as it is in C#) – Lemur Mar 31 '13 at 18:07
  • I had a similar experience as you @Pablo Lemur, when the string was not cut off properly by the substr function. – kabuto178 Mar 31 '13 at 18:20
  • @kabuto178 - yes, it's common, and it will explode pretty much every app written in C[#|++]. Besides, it's better to add `...` just to stripped strings to avoid confusion ;) – Lemur Mar 31 '13 at 18:25
0

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."....";
kabuto178
  • 3,129
  • 3
  • 40
  • 61
0

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."...\""; };
?>
Kevin Pei
  • 5,800
  • 7
  • 38
  • 55
0

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)."...";
}
Keith A
  • 771
  • 6
  • 12
0

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

Jason
  • 15,915
  • 3
  • 48
  • 72
0

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...

Pierre
  • 675
  • 1
  • 8
  • 18