Jump to content

How to display all characters until a break is reached


AdRock

Recommended Posts

I have some content in a database and i have a function to shorten the text by a set amount of characters which is useful but how would I display all the characters until a nl2br is reached?

 

Obviously it using a strpos but i don't know how i would impement it

 

Here is the function that shortens text to a given amount of characters

 

function ShortText($length, $text) {
// Change to the number of characters you want to display
$chars = $length;

$text = $text." ";
$text = substr($text,0,$chars);
$text = substr($text,0,strrpos($text,' '));
$text = $text."...";

return $text;
}

Slightly weird approach of doing it but it should work. Before i go on, you do mean, when a line-break is found, stop the string there?

 

function ShortText($fn, $text, $parameter) {

switch($fn) {
case "str":
   $text = explode($param,$text);
   $text = $text[0];
   $text = $text."...";
break;

case "snip":
// Change to the number of characters you want to display
   $chars = $param;

   $text = $text." ";
   $text = substr($text,0,$chars);
   $text = substr($text,0,strrpos($text,' '));
   $text = $text."...";
break;
}

   return $text;
}

 

This is a nice function because you can use it to snip off the string at a certain length, or snip the string off at a certain character or string. For example, a line break cut off:

ShortText("str","The Quick Brown Fox Jumps\n Over the Lazy Dog","\n");

returns:

The Quick Brown Fox Jumps...

 

Untested though...

Before i go on, you do mean, when a line-break is found, stop the string there?

Yeah...that is exactly what i mean but what yu have done is even better becuase i can use both

 

Is there a way I can change to break off at the second line break?

I'd add an extra parameter on the end called offset and then I'd default it to 0 but I dunno how you'd go about slicing off the string after the second, third etc. string, because if you just offset the part of the array you want to keep, e.g.

 

$var = explode(",","The Quick Brown Fox, Jumps Over, The Lazy Dog");

 

and you exploded it by commas, it'd be like this:

 

$var[0] : "The Quick Brown Fox"

$var[1] : " Jumps Over"

$var[2] : " The Lazy Dog"

 

Therefore you'd have to glue $var[0] & $var[1] together, which is simple, but youd need to make a sick loop to glue the right amount of keys together, depending on the offset. Im way too tired to work this out, and perhaps a better function could be used like split, preg_split, strpos & substr.

 

Hope you work it out ;)

Dan.

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.