Page 1 of 1

Limit Character Length

Posted: Thu Mar 31, 2005 1:39 pm
by ra
My script displays a chunk of text, but I want to limit the number of characters displayed (say, to 250).

Code: Select all

<?php
mysql_select_db($database_db, $db);
$query_blogs = "SELECT * FROM blogs ORDER BY blogid DESC LIMIT 0,". $blogs_to_show ."";
$blogs = mysql_query($query_blogs, $db) or die(mysql_error());
$row_blogs = mysql_fetch_assoc($blogs);
$totalRows_blogs = mysql_num_rows($blogs);
?>
<?php include("header.php"); ?>
<body>
<?php include("header2.php"); ?>
      <br>
    <table width="750" border="0" cellspacing="3" cellpadding="0">
      <tr valign="top">
        <td width="545">
		<?php if ($totalRows_blogs >= 1) { ?>
		<?php do { ?>
		<table width="545" border="0" cellspacing="0" cellpadding="1">
          <tr>
            <td><a href="<?php echo $website_url; ?>/blog_articles.php?blogid=<?php echo $row_blogs['blogid']; ?>" class="blog_title"><?php echo stripslashes($row_blogs['title']); ?></a></td>
How would i limit the number of characters displayed?

Posted: Thu Mar 31, 2005 1:48 pm
by feyd
you can limit in two places. In the query itself, or in php. With php, it allows you to more easily grab enough characters to not cut a word off. If you aren't concerned about cutting off words, SUBSTRING() in MySQL will chop the text for you.

Check the "Useful Posts" thread in my signature for a php way of not chopping off words.

SUBSTRING() :: http://dev.mysql.com/doc/mysql/en/string-functions.html

Posted: Thu Mar 31, 2005 2:10 pm
by ra
I've tried several variations found on the 'useful links' section; here is the latest:

Code: Select all

<?php echo stripslashes($row_blogs['content']);
echo substr($string, 0,30); ?></td>
No dice; where should i put said substring?

Posted: Thu Mar 31, 2005 2:11 pm
by feyd
o.O

Code: Select all

<?php
echo stripslashes($row_blogs['content']);
echo substr($row_blog['content'], 0, 30);
?>

Posted: Thu Mar 31, 2005 2:13 pm
by John Cartwright

Code: Select all

<?php $string = stripslashes($row_blogs['content']);
echo substr($string, 0,30); ?></td>
perhaps?

Posted: Thu Mar 31, 2005 2:24 pm
by ra
Phenom - you got it, thanks...

How would i add a '...' to the end of the truncated text?

Posted: Thu Mar 31, 2005 2:29 pm
by feyd
string concatenation operator; the dot. '.'

Code: Select all

echo 'hi ' . 'ra.';

Posted: Thu Mar 31, 2005 2:36 pm
by John Cartwright

Code: Select all

<?php 

$string = stripslashes($row_blogs['content']);
$string = (strlen($string) > 30) ? substr($string,0,30).'...' : $string);
echo $string; ?>

Posted: Thu Mar 31, 2005 4:17 pm
by timvw
this is how i get 20 'word' (well, groups of characters separated by a space)

Code: Select all

SELECT SUBSTRING_INDEX(content,' ',20) as short FROM data