Solved

substr end on a whole word

Posted on 2006-11-15
2
276 Views
Last Modified: 2008-02-01
I am trying to truncate a few paragraphs of text. Using this many of my paragraphs cut the middle of words

$strOut .= substr($text, 0, 60)

is there an easy way to make the string end on a space?


thanks,


R.
0
Comment
Question by:roscoeh23
2 Comments
 
LVL 49

Accepted Solution

by:
Roonaan earned 250 total points
Comment Utility
Try:

$strOut .= trim(preg_replace('/\S+$/', '', substr($text, 0, 60)));

Or

$strOut .= preg_replace('/^(.{0,60})\s(.*)$/', '\1', $text);

(Both tested, both work)

-r-
0
 
LVL 16

Assisted Solution

by:HackneyCab
HackneyCab earned 250 total points
Comment Utility
I don't think this needs regex at all.

Start off by getting the substring that contains characters zero to sixty:

$sixty_wide = substr($text, 0, 60);

then use strrpos to find the position of the last string within those sixty characters:

$last_space_pos = strrpos($sixty_wide, ' ');

then use substr again to get everything up to that last space:

$final_string = substr($sixty_wide, 0, $last_space_pos);

Hopefully that's what you're after.
0

Featured Post

Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

Join & Write a Comment

Password hashing is better than message digests or encryption, and you should be using it instead of message digests or encryption.  Find out why and how in this article, which supplements the original article on PHP Client Registration, Login, Logo…
This article discusses four methods for overlaying images in a container on a web page
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…

744 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now