Possible Duplicate:
How to select first 10 words of a sentence?
I want to show 10 words of the content words not characters
$string = 'Lorem ipsum dolor sit amet,consectetur adipiscing elit. Mauris ornare luctus diam sit amet mollis.';
should the result to be
"Lorem ipsum dolor sit amet,consectetur adipiscing elit. Mauris ornare"
Try this function:
function shorten_string($string, $wordsreturned)
{
$retval = $string;
$string = preg_replace('/(?<=\S,)(?=\S)/', ' ', $string);
$string = str_replace("\n", " ", $string);
$array = explode(" ", $string);
if (count($array)<=$wordsreturned)
{
$retval = $string;
}
else
{
array_splice($array, $wordsreturned);
$retval = implode(" ", $array)." ...";
}
return $retval;
}
On your text, so like this:
$string = 'Lorem ipsum dolor sit amet,consectetur adipiscing elit. Mauris ornare luctus diam sit amet mollis.';
$firsttenwords = shorten_string($string, 10);
From here.
UPDATE: Now it's space-compliant, and also new-line compliant.
This version will work no matter what kind of "space" you use between words and can be easily extended to handle other characters... it currently supports any white space character plus , . ; ? !
function getSnippet( $str, $wordCount = 10 ) {
return implode(
'',
array_slice(
preg_split(
'/([\s,\.;\?\!]+)/',
$str,
$wordCount*2+1,
PREG_SPLIT_DELIM_CAPTURE
),
0,
$wordCount*2-1
)
);
}
For those who should might prefer the original formatting :)
function getSnippet( $str, $wordCount = 10 ) {
return implode( '', array_slice( preg_split('/([\s,\.;\?\!]+)/', $str, $wordCount*2+1, PREG_SPLIT_DELIM_CAPTURE), 0, $wordCount*2-1 ) );
}
Try:
$str = 'Lorem ipsum dolor sit amet,consectetur adipiscing elit. Mauris ornare luctus diam sit amet mollis.';
$arr = explode(" ", str_replace(",", ", ", $str));
for ($index = 0; $index < 10; $index++) {
echo $arr[$index]. " ";
}
Output:
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris ornare
We can retrieve the words in a string using str_word_count function .
For more description about the function please refer the below link
http://php.net/manual/en/function.str-word-count.php
For displaying only 10 words in the string please refer the below code snippet
$str='Lorem ipsum dolor sit amet,consectetur adipiscing elit. Mauris ornare luctus diam sit amet mollis.';
$words=str_word_count($str,true);
$a=array_slice($words,10);
$s=join('',$a);
echo $s;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With