Solved

substr end on a whole word

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

Generating table dynamically is the most common issue faced by php developers.... So it seems there is a need of an article that explains the basic concept of generating tables dynamically. It just requires a basic knowledge of html and little maths…
Author Note: Since this E-E article was originally written, years ago, formal testing has come into common use in the world of PHP.  PHPUnit (http://en.wikipedia.org/wiki/PHPUnit) and similar technologies have enjoyed wide adoption, making it possib…
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
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…

756 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