mitzleah Posted September 21, 2006 Share Posted September 21, 2006 Hey Guys,I need to trim a sentence based on its word content. For example I only want to display 50 words. In a string this would be:substr($str, 0, 50);My question is how about in word? Thanks! Link to comment https://forums.phpfreaks.com/topic/21502-word-trimming-help/ Share on other sites More sharing options...
paul2463 Posted September 21, 2006 Share Posted September 21, 2006 $wordCount = 0;$charCount = 0;$str = "Hello World";for ($i=0; $i<1000;$i++) { // no sentence with 50 words is going to be longer than 1000 characters if ( $str[$i] == " "){ // if the character is a space i.e end of word $wordCount ++; $charCount ++; if($wordCount == 50) { break;}} else { // if its a letter then it is still in the word $charCount ++; }}$newstr = substr($str, 0, $charCount); Link to comment https://forums.phpfreaks.com/topic/21502-word-trimming-help/#findComment-95890 Share on other sites More sharing options...
mitzleah Posted September 21, 2006 Author Share Posted September 21, 2006 @paul2463Thanks! :) Link to comment https://forums.phpfreaks.com/topic/21502-word-trimming-help/#findComment-96373 Share on other sites More sharing options...
Barand Posted September 21, 2006 Share Posted September 21, 2006 or[code]<?php$word_array = explode (' ', $text);$first50 = join(' ', array_slice ($word_array, 0, 50));echo $first50;?>[/code] Link to comment https://forums.phpfreaks.com/topic/21502-word-trimming-help/#findComment-96389 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.