I have a long string which is actually a paragraph. Can I have php only include the first X number of full words from the string? Ideally, I'd like to include the number of words closest to, say, the 80-character point. How could I search for a space near that point? I know I can *count* words, but is there a way to have a substring of X many words? Thanks! Example: $paragraph = "This is my dummy paragraph that includes no important facts and in fact I am making it all up off the top of my head. I trust it was enjoyed by all." My web site displays: "This is my dummy paragraph that includes no important facts and" But $paragraph changes depending on the page, so I can't just lop it off at a certain number of characters.
function substr_words ($paragraph, $num_words) { $paragraph = explode (' ', $paragraph); $paragraph = array_slice ($paragraph, 0, $num_words); return implode (' ', $paragraph); } PHP: Or, maybe something like this would suit your needs better. function cut_paragraph ($paragraph, $limit=80) { $pos = strrpos ($paragraph, ' ', $limit); if (false !== $pos) { return substr ($paragraph, 0, $pos); } return $paragraph; } PHP:
$paragraph = "This is my dummy paragraph that includes no important facts and in fact I am making it all up off the top of my head. I trust it was enjoyed by all."; $rough_short_par = substr($paragraph, 0, 80); //chop it off at 80 $last_space_pos = strrpos($rough_short_par, " "); //search from end: http://uk.php.net/manual/en/function.strrpos.php $clean_short_par = substr($rough_short_par, 0, $last_space_pos); // add three dots... $clean_sentence = $clean_short_par . "...(read more)"; //could link the read more to full article echo $clean_sentence; PHP:
Thanks guys! T0PS3O, I tried yours first and it works great. Sorry I didn't get a chance to test yours, exam What a great thing php is
I'm trying to implement the solution below to return a set number of words of a string but I'm a noobie and I'm not quite sure how to implement it. Right now, the output is generated with <?php echo cOut($row[8]); ?> PHP: since the data resides in row 8 of the database table. This returns all of the data but what I want is just the 1st 20 or 30 words. Any suggestions on how to get this to work for me?