Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

substr end on a whole word

Posted on 2006-11-15
2
Medium Priority
?
301 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

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Question has a verified solution.

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

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…
Part of the Global Positioning System A geocode (https://developers.google.com/maps/documentation/geocoding/) is the major subset of a GPS coordinate (http://en.wikipedia.org/wiki/Global_Positioning_System), the other parts being the altitude and t…
The viewer will learn how to dynamically set the form action using jQuery.
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…
Suggested Courses

636 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