Jump to content

Archived

This topic is now archived and is closed to further replies.

mitzleah

Word Trimming Help

Recommended Posts

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!

Share this post


Link to post
Share on other sites
$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);

Share this post


Link to post
Share on other sites
or

[code]
<?php
$word_array = explode (' ', $text);
$first50 = join(' ', array_slice ($word_array, 0, 50));

echo $first50;
?>
[/code]

Share this post


Link to post
Share on other sites

×

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.