note 55865 modified in function.str-word-count by danbrown

From: Date: Fri, 31 Aug 2012 16:28:31 +0000
Subject: note 55865 modified in function.str-word-count by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-190374@lists.php.net to get a copy of this message
Here&#39;s a function that will trim a $string down to a certian number of words, and add a... on the end of it.&#13;&#10;(explansion of muz1&#39;s 1st 100 words code)&#13;&#10;&#13;&#10;----------------------------------------------&#13;&#10;&#60;?php&#13;&#10;function trim_text($text, $count){&#13;&#10;$text = str_replace(&#34; &#34;, &#34; &#34;, $text);&#13;&#10;$string = explode(&#34; &#34;, $text);&#13;&#10;for ( $wordCounter = 0; $wordCounter &#60;= $count;wordCounter++ ){ &#13;&#10;$trimed .= $string[$wordCounter];&#13;&#10;if ( $wordCounter &#60; $count ){ $trimed .= &#34; &#34;; }&#13;&#10;else { $trimed .= &#34;...&#34;; }&#13;&#10;}&#13;&#10;$trimed = trim($trimed);&#13;&#10;return $trimed;&#13;&#10;}&#13;&#10;?&#62;&#13;&#10;&#13;&#10;Usage&#13;&#10;------------------------------------------------&#13;&#10;&#60;?php&#13;&#10;$string = &#34;one two three four&#34;;&#13;&#10;echo trim_text($string, 3);&#13;&#10;?&#62;&#13;&#10;&#13;&#10;returns:&#13;&#10;one two three... --was-- Here's a function that will trim a $string down to a certian number of words, and add a... on the end of it. (explansion of muz1's 1st 100 words code) ---------------------------------------------- function trim_text($text, $count){ $text = str_replace(" ", " ", $text); $string = explode(" ", $text); for ( $wordCounter = 0; $wordCounter <= $count;wordCounter++ ){ $trimed .= $string[$wordCounter]; if ( $wordCounter < $count ){ $trimed .= " "; } else { $trimed .= "..."; } } $trimed = trim($trimed); return $trimed; } Usage ------------------------------------------------ $string = "one two three four"; echo trim_text($string, 3); returns: one two three... http://php.net/manual/en/function.str-word-count.php

« previous php.notes (#190374) next »