0

i have this:

<? if (strlen($item->introtext) > 300) { 
    echo substr($item->introtext, 0,300)." More"; 
    } else { 
    echo $item->introtext;}
?>

But it counts symbols, i want it to count words. E.g. after 10th word to add "More".

How to do this, i guess I must change "strlen" with smthing else?

user1978483
  • 89
  • 2
  • 4
  • 13
  • Looks like you want something like this... http://stackoverflow.com/questions/79960/how-to-truncate-a-string-in-php-to-the-word-closest-to-a-certain-number-of-chara – Rob Feb 07 '13 at 12:36

3 Answers3

4

Use function str_word_count(). Which will gave count as well as array of words as per second argument. For more info

Madara's Ghost
  • 172,118
  • 50
  • 264
  • 308
kuldeep.kamboj
  • 2,566
  • 3
  • 26
  • 63
  • 1
    I tried to use this function, but i cannot make it work... Can you provide/show a example – user1978483 Feb 07 '13 at 12:39
  • @user1978483: The manual page linked has the examples you need. Also, next time, when you ask a question, make sure to mention what you've tried in order to solve the problem. – Madara's Ghost Feb 07 '13 at 12:39
  • Second argument set as 0 will give count of words. ( As manual page says :) ) – kuldeep.kamboj Feb 07 '13 at 12:45
  • Dont you think if I asked such a simple question, that means I am not a php programmer? You tell me to look at the example form your link, I realy dont get it there... But anyway its okey, let's count this question CLOSED. – user1978483 Feb 07 '13 at 12:53
1

You can split by a space, and count how many words you have:

$words = preg_split("/\s+/", $string, null, PREG_SPLIT_NO_EMPTY);

Note:

  • I use preg_split to overcome the consecutive spaces problem.
  • PREG_SPLIT_NO_EMPTY doesn't include empty words.

$words now contains an array of all words, you can count() it to know how many you have, and array_slice() and implode() to get a string back from it.

Madara's Ghost
  • 172,118
  • 50
  • 264
  • 308
0

You could explode the string on spaces. That should give you an array with entries for every word. A count of the array would then tell you the amount of words. There could be some false-positives with this technique since everything that is surrounded by [space] would count as a word.

Tarilo
  • 430
  • 2
  • 6
  • You aren't taking into account what happens when multiple spaces are used consecutively. – Madara's Ghost Feb 07 '13 at 12:36
  • Yes, that's why is said that this method isn't exact. Though a better answer has aleady been given. Use the build in function str_word_count – Tarilo Feb 07 '13 at 12:38