limit echo characters

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
spikey246
Forum Newbie
Posts: 5
Joined: Tue Mar 31, 2015 3:24 am

limit echo characters

Post by spikey246 »

Hi all.

I am extracting some data by using

Code: Select all

{$row->content}
Is there a way I can limit how many characters are displayed? Has a lot of text only want say 100 displayed. Any ideas?
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: limit echo characters

Post by Celauran »

spikey246
Forum Newbie
Posts: 5
Joined: Tue Mar 31, 2015 3:24 am

Re: limit echo characters

Post by spikey246 »

Celauran wrote:substr
It works well for something like

Code: Select all

<?php echo substr($row['content'], 0, 200); ?>
But how do you implement it with:

Code: Select all

{$row->content}
This is placed within an echo. Example below.

Code: Select all

$results = $db->query($sql);

if($results->num_rows) {
	While($row = $results->fetch_object()) {
		echo "
		
<div class='snippets'>
	<div class='content'><h5>{$row->content}</h5>
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: limit echo characters

Post by Celauran »

It works exactly the same way.

Code: Select all

<?php if ($results->num_rows): ?>
	<?php while ($row = $results->fetch_object()): ?>
		<div class="snippets">
			<div class="content">
				<h5><?= substr($row->content, 0, 200); ?></h5>
				More stuff
			</div>
		</div>
	<?php endwhile; ?>
<?php endif; ?>
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Re: limit echo characters

Post by Christopher »

When embedding array elements or object properties, using curly braces help the parser delineate the variable (e.g., "{$row->content}" or "{$row['content']}".). It is necessary with array elements or object properties, but can also help when a variable is ambiguous like $foo in " $fooabc " which would need to be " {$foo}abc ".

There are other ways to achieve the same thing that Celauran showed with embedded tags. Pick the one that suits your needs.

Code: Select all

// concatenation
echo "<div class='content'><h5>" . substr($row->content, 0, 200) . "</h5>";
// temporary variable
$content = substr($row->content, 0, 200);
echo "<div class='content'><h5>$content</h5>";
(#10850)
Post Reply