Truncate an Echo

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
AliasBDI
Forum Contributor
Posts: 286
Joined: Fri Nov 15, 2002 10:35 am
Location: Spring, TX, USA

Truncate an Echo

Post by AliasBDI »

I have an echo from a search query. The code reads:

Code: Select all

<?php echo $row_recordLIST['content']; ?>
The result is way too long (like 5,000 characters of text). I want to shorten it so that it only shows like 300 characters and follows them with a '...' to let the view know that there is more. I believe this is called truncating, but I cannot figure out how to do it.
timvw
DevNet Master
Posts: 4897
Joined: Mon Jan 19, 2004 11:11 pm
Location: Leuven, Belgium

Post by timvw »

substr...... php has it, and i think mysql has it too (could be called substring there)
AliasBDI
Forum Contributor
Posts: 286
Joined: Fri Nov 15, 2002 10:35 am
Location: Spring, TX, USA

Thanks.

Post by AliasBDI »

Works with 'substr'. Here is my new code:

Code: Select all

<?php $content = $row_recordLIST['content']; $content = substr($content, 0, 1000); echo $content . "..."; ?>
The truncating happens in "substr($variable, 0, 1000)". The first number is for the beginning of the line. The second is the cut off the end of the line. So it is removing -1 and back (which is nothing) and 1001 and forward. Basically cutting the ends off the result. I added the "..." just to let the user know that there was more.

Thanks for your help.
timvw
DevNet Master
Posts: 4897
Joined: Mon Jan 19, 2004 11:11 pm
Location: Leuven, Belgium

Post by timvw »

i mentionned that mysql has substring too, because it would be useless to transfer +10k characters, if you only need 50 or so...


Say, i want to show the 20 first words of a column named content

Code: Select all

SELECT SUBSTRING_INDEX(content,' ',20) AS content FROM table;
Post Reply