Solved

substr end on a whole word

Posted on 2006-11-15
2
288 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 250 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 250 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

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

Popularity Can Be Measured Sometimes we deal with questions of popularity, and we need a way to collect opinions from our clients.  This article shows a simple teaching example of how we might elect a favorite color by letting our clients vote for …
I imagine that there are some, like me, who require a way of getting currency exchange rates for implementation in web project from time to time, so I thought I would share a solution that I have developed for this purpose. It turns out that Yaho…
The viewer will learn how to count occurrences of each item in an array.
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.

691 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