Jump to content


Photo

Word Trimming Help


  • Please log in to reply
3 replies to this topic

#1 mitzleah

mitzleah
  • Members
  • PipPipPip
  • Advanced Member
  • 31 posts
  • LocationManila, Philippines

Posted 21 September 2006 - 06:33 AM

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!

#2 paul2463

paul2463
  • Members
  • PipPipPip
  • Advanced Member
  • 955 posts
  • LocationUK

Posted 21 September 2006 - 06:53 AM

$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);


you cannot affect the past but you can ruin a perfectly good present by worrying about the future

*********************************************************************
The <A HREF="http://www.php.net/d...php">MANUAL</A> is actually a useful resource

#3 mitzleah

mitzleah
  • Members
  • PipPipPip
  • Advanced Member
  • 31 posts
  • LocationManila, Philippines

Posted 21 September 2006 - 10:45 PM

@paul2463

Thanks! :)

#4 Barand

Barand
  • Moderators
  • Sen . ( ile || sei )
  • 18,017 posts

Posted 21 September 2006 - 11:18 PM

or

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

echo $first50;
?>

If you are still using mysql_ functions, STOP! Use mysqli_ or PDO. The longer you leave it the more you will have to rewrite.

Donations gratefully received






moon.png

|baaGrid| easy data tables - and more
|baaChart| easy line, column and pie charts




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users