Reputation: 857
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
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
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
Reputation: 2665
...
to your stringCode:
if (strlen($string) > 20) {
$string = substr($string, 0, 20) . "..."; }
Upvotes: 4
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
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
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