1

I`m trying to do the next task: I have a string, for ex. "Product with a very long name so that it goes on to more than one line". I want to make next customization: if a number of charackters in the string (without spaces) will be more than 22, cut it on the last word, and add "...".

volodymyr3131
  • 335
  • 2
  • 5
  • 16
  • 2
    Cool, then do it. If you don't know how, post your current code and ask a question. – Prinzhorn Mar 04 '14 at 13:01
  • ^ The answer I gave in this question includes a much prettier CSS solution, which factors in the fact that llllllllll is nowhere near as "long" as WWWWWWWWWW. – Niet the Dark Absol Mar 04 '14 at 13:03
  • I have read your solution with CSS. But, how does the browser know how many characters I want to left? And, will it be cross-browser solution? – volodymyr3131 Mar 04 '14 at 13:12
  • But, as I understand, it will cut the string at the 50 character in your example. And I need the last word to be full – volodymyr3131 Mar 04 '14 at 13:39
  • I think what you are looking for is some think like http://webwidetutor.com/php/substring/ – Mubo Mar 04 '14 at 14:24
  • A have already found answer: http://stackoverflow.com/a/17702942/2938377 – volodymyr3131 Mar 04 '14 at 14:40
  • The answer I found abowe is not quite right(( This algoritm cut the phrase after 22 symbols, including spaces. But I need to count 22 symbols in text without spaces, and then add '...' after the last full word. Please, has anyone some ideas? – volodymyr3131 Mar 06 '14 at 12:03

3 Answers3

1
<?php
  if(strlen($yourString) > 22)
    $rest = substr($yourString, 22,-1)."...";
  else
    $rest = $yourString;
  echo $rest;
?>

If you want that last word doesn't cut then,

<?php
$yourString = "bla blaaa bla blllla bla bla";
$out = "";
if(strlen($yourString) > 22) {
    while(strlen($yourString) > 22) {
        $pos = strrpos($yourString, " ");
        if($pos !== false && $pos <= 22) {
            $out = substr($yourString,0,$pos);
            break;
        } else {
            $yourString = substr($yourString,0,$pos);
            continue;
        }
    }
} else {
    $out = $yourString;
}
echo "Output String: ".$out;
?>
Jaykishan
  • 1,409
  • 1
  • 15
  • 26
0
if(strlen($myString)>=22)
{
  $result = substr($myString, 0, 22)."...";
}
else
{
  $result = $myString;
}
user2706194
  • 199
  • 8
-1

You can do like this:

<?php
$text = "A very long woooooooooooord.";
if(strlen($text) > 22 ) {
 echo substr($text, 1, 22)."..";
} else {
echo $text;
}

?>
Suresh Kamrushi
  • 15,627
  • 13
  • 75
  • 90