Hi all, I'm a newbie working with PHP - so PLEASE be gentle!
I need to limit the amount of information displayed when viewing results then being taken to a READ MORE link for the full story
i.e "My news story goes here . . . READ MORE"
I am currently using
<?php echo substr ($row_news['title'],0,40); ?>
which nicely limits the displayed characters to 40.
Unfortunately, it breaks in the middle of words - which looks terrible.
How do I return these limited results without breaking complete words in the middle?
Have looked for answers elsewhere, but am presented with pages of code, with no indication of what to do with it!
Many thanks for any help
Newbie help with substr - limit without breaking words
Moderator: General Moderators
Re: Newbie help with substr - limit without breaking words
note there is probably a better method, but you could try a regex..
Code: Select all
<?php
$row_news['title'] = "Fly me to the moon, let me play amongst the star and let me see what script is like";
// Match upto 40 letters, but finish on the last word
preg_match("!^.{0,40}\w{0,}!", $row_news['title'], $matched);
print_r($matched);
echo "<Br><Br>";
echo $matched[0];
echo "<br>Total length: " . strlen($matched[0]);
?>
Re: Newbie help with substr - limit without breaking words
That would be a nice solution, but what if the string is "Fly me to the moon, let me play supercallafragilistexpealadous."? Shouldn't it match at most 40 characters rather than at least?
Re: Newbie help with substr - limit without breaking words
many thanks for your help so far - it's looking better but now showing this:
Array ( [0] => My news story headline )
Like I say - I'm only a newbie and obviously doing something wrong!
Jonny
Array ( [0] => My news story headline )
Like I say - I'm only a newbie and obviously doing something wrong!
Jonny