Jump to content

limit textfield to three strings


MDanz

Recommended Posts

Alright I just did some searching on google and found what your looking for. This does something similar to what you want. I'm sure you could edit it to your liking.

Step 1 of 2
<?php
   
function drupalicious_summarise($paragraph, $limit)
{
       $textfield = strtok($paragraph, " ");
       while($textfield)
       {
           $text .= " $textfield";
           $words++;
           if(($words >= $limit) && ((substr($textfield, -1) == "!")||(substr($textfield, -1) == ".")))
               break;
           $textfield = strtok(" ");
       }
       return ltrim($text);
    }
?>

Step 2 of 2
<?php print drupalicious_summarise($textfieldname,20);?>

$textfieldname = the name of the field you want trimmed.
20 = the number of words, to the nearest sentance, your text will be trimmed to.

I think I'd use explode, array_chunk, and implode for this one (whether it's the best way or not, I'm not sure). I briefly tested this, and it seems to so what you're after.

 

<?php
$string = 'Giant bunch of words and stuff';
$array = array_chunk(explode( ' ', $string), 3);
$new_string = implode( ' ', $array[0] );
echo $new_string;  // Echos "Giant bunch of"
?>

 

EDIT: If the original string is coming from a database query, you might be able to do this more efficiently using MySQL's built in SUBSTRING_INDEX() function.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.