Function GetValidChars Question Please

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Az_Critter
Forum Newbie
Posts: 11
Joined: Wed Oct 28, 2009 8:35 am

Function GetValidChars Question Please

Post 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
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Re: Function GetValidChars Question Please

Post 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;
}
Az_Critter
Forum Newbie
Posts: 11
Joined: Wed Oct 28, 2009 8:35 am

Re: Function GetValidChars Question Please

Post by Az_Critter »

That works wonderfully! Thanks very much for your help, John! :D
Post Reply