views:

167

answers:

3

I am building an RSS script with mysql, and i dont want an extra field in the database... i want to shrink down the body of the article with a "... Read More" but im not sure how i can limit the number of chars echoed out onto the page?

Of course not this syntax, but something along the lines of:

echo(limit($row['newsBody'], 1000));

I dont mind if it takes 15 lines of code to do this ;)

P.S. I am sure limit() is a function, please dont tell me .. its just an example ;)

Thanks in advanced!

+3  A: 
echo(substr($row['newsBody'], 0, 1000));

The substr function is what you are looking for. Or you can use mb_substr if you are dealing with multi-byte strings.

Ayman Hourieh
+1  A: 
substr( $string, 0, 1000 );
Kendall Hopkins
+3  A: 

You could do this

$body = $row['newsBody'];
$length = strlen($body) > 1000 ? 1000 : strlen($1000);
echo substr($body,0, $length);

It'll print the first 1000 characters or the whole message which ever is shorter

aip.cd.aish
+1 for the fall-back *or whichever is shorter* consideration.
David Thomas
The `strlen()` check is not necessary as `substr($s, 0, $length)` returns at most `$length` chars depending on the length of `$s`. http://php.net/manual/en/function.substr.php
Ayman Hourieh
Ah yes, true. :)I'll just leave it here since it might give someone the idea to do checks like this in other cases where it may matter.
aip.cd.aish