Newbie help with substr - limit without breaking words

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
jonspall
Forum Newbie
Posts: 2
Joined: Mon Aug 03, 2009 7:36 am

Newbie help with substr - limit without breaking words

Post by jonspall »

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
kelv1n
Forum Newbie
Posts: 4
Joined: Sun Oct 14, 2007 1:05 pm

Re: Newbie help with substr - limit without breaking words

Post by kelv1n »

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]);
?>
 
User avatar
onion2k
Jedi Mod
Posts: 5263
Joined: Tue Dec 21, 2004 5:03 pm
Location: usrlab.com

Re: Newbie help with substr - limit without breaking words

Post by onion2k »

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?
jonspall
Forum Newbie
Posts: 2
Joined: Mon Aug 03, 2009 7:36 am

Re: Newbie help with substr - limit without breaking words

Post by jonspall »

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
Post Reply