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! Quote Link to comment 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); Quote Link to comment Share on other sites More sharing options...
mitzleah Posted September 21, 2006 Author Share Posted September 21, 2006 @paul2463Thanks! :) Quote Link to comment 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] Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.