Page 1 of 1
limit echo characters
Posted: Wed Apr 01, 2015 4:31 am
by spikey246
Hi all.
I am extracting some data by using
Is there a way I can limit how many characters are displayed? Has a lot of text only want say 100 displayed. Any ideas?
Re: limit echo characters
Posted: Wed Apr 01, 2015 7:15 am
by Celauran
Re: limit echo characters
Posted: Wed Apr 01, 2015 8:00 am
by spikey246
It works well for something like
Code: Select all
<?php echo substr($row['content'], 0, 200); ?>
But how do you implement it with:
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>
Re: limit echo characters
Posted: Wed Apr 01, 2015 9:21 am
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; ?>
Re: limit echo characters
Posted: Wed Apr 01, 2015 10:41 am
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>";