View Full Version : text - cut off at the nearest space

01-14-2004, 07:45 AM
To grab only the first 150 characters from a mySQL table field containing text I use the following:


.. in my SQL select statement.

Unfortunately this tends to cut out in the middle of words though which isn't to great.

Is there a simple-ish using php I make it cut off at the nearest space?

01-14-2004, 08:02 AM
if you wanted to grab say the first $x words you could use MySQL's SUBSTRING_INDEX...

e.g. first 20 words ...
SELECT SUBSTRING_INDEX( fieldname ,' ', 20 ) ;

in PHP would probably be messy compared to the above ... something like ??

(untested and cheesy :: might ;) give you a string between 150 - 164 chars)

$pre = substr( $str , 0 ,148 );
/*assuming most words are less than 15 chars*/
$ext = substr( $str , 149 , 15 );
$bits = explode( ' ' , $ext ) ;

echo $pre . $bits[0];

though perhaps there is some funky regex to do the same ?
MySQL would still be the best bet from a performace perspective

01-14-2004, 08:18 AM
errr actually ignore that ;)

this does work & gives a max of 150 chars

$pos = strrpos( substr( $str , 0 , 150 ) ,' ' ) ;
echo substr( $str , 0 , $pos );

01-14-2004, 10:26 AM
I see.. thank you. :thumbsup:

01-14-2004, 03:40 PM
And I also wrote this for someone on here long ago which does basically the same thing except it parses the string and allows you to remove imperfections and attempts to cut the string off at the nearest sentence but under the word limit.

<form name="foo" method="post" action="<?php echo $PHP_SELF ?>">
<textarea name="input" cols="50" rows="6" wrap="VIRTUAL" id="input"></textarea>
<input type="submit" name="Submit" value="Submit">

$input = $_POST["input"];

function process_string($string) {

// Number of words to return.
$word_limit = 5;

// Remove line breaks, double spaces, etc from the string
// You can add to this section to clean up the string
// before attempting to count the number of words.
$string = str_replace("\n"," ",$string);
$string = str_replace(" "," ",$string);

// Split the string into an array of words.
// It is set to split when a single space is found
$word_array = explode(" ", $string);

// Counts the number of elements in the array
// which should be about how many words were in the string
$num_of_words = count($word_array);

// Trims the array of words. Removes all words after
// what is specified in the $word_limit
$word_array_trimmed = array_splice ($word_array, 0, $word_limit);

// Converts the array of words back into a string
$final_string = implode(" ",$word_array_trimmed);

return $final_string;

echo "<br><br>" . process_string($input);


It determines sentences based on periods being at the end of the sentence however there are some situations that will break that logic such as periods being used other than at the end of a sentence.