?
Solved

substr end on a whole word

Posted on 2006-11-15
2
Medium Priority
?
296 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
2 Comments
 
LVL 49

Accepted Solution

by:
Roonaan earned 1000 total points
ID: 17945670
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 1000 total points
ID: 17947522
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

Video: Liquid Web Managed WordPress Comparisons

If you run run a WordPress, you understand the potential headaches you may face when updating your plugins and themes. Do you choose to update on the fly and risk taking down your site; or do you set up a staging, keep it in sync with your live site and use that to test updates?

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Developers of all skill levels should learn to use current best practices when developing websites. However many developers, new and old, fall into the trap of using deprecated features because this is what so many tutorials and books tell them to u…
Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn how to count occurrences of each item in an array.
Suggested Courses

777 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