RE: preview string with strlen PHP (help)

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



> -----Original Message-----
> From: Dwayne Heronimo [mailto:dwayne@xxxxxxxxxxxxxxx]

> Dear All,
>
> I am very new to programming. I want to make a preview text that would
> display only a part of the text that is a text field in a database.
>
> //Begin Make preview string
>
>  $minitxt = $row_show_cat['text'];
>  $len = strlen($minitxt);
>
>  if ($len > 235)
>  {
>   $len = 235;
>  }
>  else
>  {
>   $len = $len;
>  }
>
>  $newstring = substr($minitxt,0,$len);
>
>  $previewtext = $newstring;
>
> //End Make preview string
>
> But if I want to display this somewhere in the page it will only
> display the
> first record of at every text column row <?php echo $previewstext ?>
>
> Althought I am very new to php and programming. I thought maybe I should
> rewrite it into a function. But my function won't work.
>
>
> function previewString($showcatvar) {
>
>  $minitxt = $showcatvar;
>  $len = strlen($minitxt);
>
>  if ($len > 235)
>  {
>   $len = 235;
>  }
>  else
>  {
>   $len = $len;
>  }
>
>  $newstring = substr($minitxt,0,$len);
>
>  $previewtext = $newstring;
>
>  $previewtext = $whowcatvar;
>
> }
>
>
> and to display it in the page:
>
> <?php echo  previewString($row_show_cat['text']) ?>
>
> IT displays notthing. But I think I am doing somthing wrong. I am
> assigning
> the wrong variables to the $row_show_cat['text']) ???
>
> Please let me know

Hi Dwayne,

Your function isn't working as you expect because you are not returning any
value. I would rewrite it as:

function previewString($strInput) {
	// Max length allowed
	// You could also store this in a config file or pass in as
	// a second, possibly optional argument.
	$intMaxLen = 235;

	if (strlen($strInput) > $intMaxLen) {
		// Too long so trucate it (and add ... to show
		// it is truncated. I subtract 3 to allow for ...)
		return substr($strInput, 0, ($intMaxLen-3)).'...'
	}

	// If we get here it is less than or equal to the allowed max so just
return it
	return $strInput;
}

You would then call the function when you needed the truncated string, e.g.
<?php echo previewString($previewstext); ?>

If you are outputting this to a web page, you'll probably also want to pass
it through the htmlentities function: <?php echo
htmlentities(previewString($previewstext)); ?>

Good luck,
Edward

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux