Page 1 of 1

Function GetValidChars Question Please

Posted: Fri Sep 10, 2010 10:53 am
by Az_Critter
In my function files I have this;

function getValidChars($data,$enum){
$inTag = false;
$returning = '';
$num = 0;
for ($i = 0; $i < strlen($data); $i++){
$current = substr($data,$i,1);
if (!$inTag){
if ($current == "<") $inTag = true;
else $num++;}
else{
if ($current == ">") $inTag = false;}
$returning .= $current;
if ($num >= $enum) return $returning;}}


Then in another file, where I call data from the database, I have this;

$i = getValidChars("variable name here",20);
variable name here = $i;


This code sets up a preview of a larger field of text, so that players can get a small glimpse of the entire text.
This code seems to work great, if the larger text contains 20 or more characters, as it returns the preview I'm looking for. However, if the larger text field actually contains less characters than 20, it seems to create a blank, or non-existent preview.
So the question is, how can I change the code above, to create the preview I'm looking for, in both cases, without going over 20 characters in the outcome?

I hope I've explained it well. If not, feel free to ask me questions. I'll check back periodically.
Thanks for your help again,
Az_Critter :D

Re: Function GetValidChars Question Please

Posted: Fri Sep 10, 2010 11:25 am
by John Cartwright
I would generally strip all the tags prior to truncating the text, since this may lead to severely undesired behavior.

I.e.,

Code: Select all

function getValidChars($data, $limit) 
{
   $newdata = strip_tags($data);
   if (strlen($newdata ) > $limit) { 
      return substr($newdata, 0, $limit) .' ... ';
   } 
   return $newdata;
}

Re: Function GetValidChars Question Please

Posted: Fri Sep 10, 2010 11:39 am
by Az_Critter
That works wonderfully! Thanks very much for your help, John! :D