0

Possible Duplicate:
How to get first x chars from a string, without cutting off the last word?
php trim a string

My issue is that i need cut a string down to less than 30 characters whilst also making sure that the string finishes on a word.

I have been using this:

$slidedescription = substr($slidedescription,0,30).'...';

The problem is that it can cut into the string mid word. Is there any simple way to make sure that it finished on a word but it less than 30 characters long?

Community
  • 1
  • 1
Undefined
  • 11,234
  • 5
  • 37
  • 62
  • It is a duplicate. That question has the answer i seek. – Undefined Jan 31 '12 at 11:19
  • @SamWarren i have edited my answer and added a function and with few more examples. if the string has a word which is more than 30 chars it's still works as your original solution as in the beginning though – mirza Jan 31 '12 at 11:52

2 Answers2

1

There can be many unexpected situations i tried to cover as many as i can them up:

<?

    $string_1  = "anavaragelongword shortword";
    $string_2 = "averylongwordwhichisprobablymorethan30characters word1";
    $string_3 = "word2 word3 averylongwordwhichisprobablymorethan30characters";
    $string_4 = "three avarege words";

    $char_length = 30;
    echo slidedescription($string_1, $char_length);
    echo slidedescription($string_2, $char_length);
    echo slidedescription($string_3, $char_length);
    echo slidedescription($string_4, $char_length);

    function slidedescription($string, $char_length)
    {   
    $total_length = null;
    $slidedescription = null;

    $length = strlen($string);
    if($length>$char_length) { 

    $array = explode(" ", $string);
    foreach ($array as $key => $value) {
    $value_length[$key] = strlen($value);
    $total_length = $total_length + $value_length[$key];
    if ($total_length<=$char_length) {
    $slidedescription .= $value." "; 
    }
    if (!$slidedescription) {
    $slidedescription = substr($value,0,$char_length).'...';
    }
    }
    } else {
    $slidedescription = $string; 
    }

    $last = trim($slidedescription).'... <br />';
    return $last;
    }
mirza
  • 5,685
  • 10
  • 43
  • 73
0

you could try looking for the last position where a space occurs using

strrpos

you could use it like so :

$spacelocation = strrpos($slidedescription, " ");

if($spacelocation != false)
{
    if($spacelocation < 30)
    {
        $slidedescription = substr($slidedescription,0,$spacelocation).'...';
    }
}
else
{
    $slidedescription = substr($slidedescription,0,30).'...';
}
Timothy Groote
  • 8,614
  • 26
  • 52