georgevich
georgevich

Reputation: 2485

Limit words of string - UTF8

Can you explain me how to display let`s say first 10 words of string which contains of 20 words. I have a function which deals good with non utf8 letters, but how to do that with utf8 letters ?

Upvotes: 3

Views: 1529

Answers (2)

Gumbo
Gumbo

Reputation: 655239

You could split your string into words and word-separators and then grab the first ten words from it:

$parts = preg_split('/(\p{L}+)/u', $str, -1, PREG_SPLIT_DELIM_CAPTURE);
$excerpt = implode('', array_slice($parts, 0, 20));

Upvotes: 3

user336242
user336242

Reputation:

Would something like

explode() - Split a string by string

be your friend?

http://www.php.net/manual/en/function.explode.php

$words = "My String that contains over ten words etc etc etc etc";
$wordArray = explode(' ', $words);

$summary = array();
for($i = 0; $i < 10; $i++){
   $summary[] = $wordArray[$i];
}

$summary = implode(' ', $summary);
echo $summary;

Or you could use

strtok - Tokenize string

https://www.php.net/manual/en/function.strtok.php

Upvotes: 0

Related Questions