views:

3198

answers:

9

How can I truncate a string after 20 words in PHP?

+2  A: 

Split the string (into an array) by <space>, and then take the first 20 elements of that array.

lance
which function would i use to split?
sanders
exactly what you said, the split function http://us3.php.net/split
yx
http://us.php.net/split
lance
won't work if there are punctuations but with no space after them, such as "hello,world".
動靜能量
@Jian Lin That's a problem with the user entering poor data, not the script.
ceejayoz
@Jian just define your delimiter to be all punctuation (,.;) etc
yx
@ceejayoz shouldn't the script handle bad user data too?
動靜能量
User input is an assumption that might be false?
lance
+3  A: 

This looks pretty good to me:

A common problem when creating dynamic web pages (where content is sourced from a database, content management system or external source such as an RSS feed) is that the input text can be too long and cause the page layout to 'break'.

One solution is to truncate the text so that it fits on the page. This sounds simple, but often the results aren't as expected due to words and sentences being cut off at inappropriate points.

Andrew Hare
+1  A: 

Try regex.

You need something that would match 20 words (or 20 word boundaries).

So (my regex is terrible so correct me if this isn't accurate):

/(\w+\b){20}/

And here are some examples of regex in php.

Assaf Lavie
+2  A: 
function limit_text($text, $limit) {
      if (strlen($text) > $limit) {
          $words = str_word_count($text, 2);
          $pos = array_keys($words);
          $text = substr($text, 0, $pos[$limit]) . '...';
      }
      return $text;
    }

echo limit_text('Hello here is a long sentence blah blah blah blah blah hahahaha haha haaaaaa', 5);

Outputs:

Hello here is a long ...
karim79
This function confuses character count and word count when using $limit in one case as a word selector of the array $pos and in another by determining if the string is long enough.
Tegeril
In the example provided, passing in a value of 5 ensures that the function will act on any word of length greater than 5 characters, so had the test case been "Hello here", the function fails and returns only "..."
Tegeril
@Tegeril - noted, will delete this post. Thank you.
karim79
A: 

Something like this could probably do the trick:

<?php 
$words = implode(' ', array_slice(split($input, ' ', 21), 0, 20));
mikl
+1  A: 

use explode() .

Example from the docs.

// Example 1
$pizza  = "piece1 piece2 piece3 piece4 piece5 piece6";
$pieces = explode(" ", $pizza);
echo $pieces[0]; // piece1
echo $pieces[1]; // piece2

note that explode has a limit function. So you could do something like

$message = implode(" ", explode(" ", $long_message, 20));
Matthew Vines
+1 WOW, I've been using explode since ever and I've never noticed the $limit argument before.
Alix Axel
Explode's limit function does not act as suggested in this context. See http://www.php.net/manual/en/function.explode.php Example #2, positive limit.
Tegeril
+1  A: 

use PHP tokenizer function strtok() in a loop.

$token = strtok($string, " "); // we assume that words are separated by sapce or tab
$i = 0;
$first20Words = '';
while ($token !== false && $i < 20) {
    $first20Words .= $token;
    $token = strtok(" ");
    $i++;
}
echo $first20Words;
farzad
+3  A: 

change the "2" to 19 to get first 20 words. This one gets the first 3 words:

function first3words($s) {
    return preg_replace('/((\w+\W*){2}(\w+))(.*)/', '${1}', $s); 
}

var_dump(first3words("hello yes, world wah ha ha"));  # => "hello yes, world"
var_dump(first3words("hello yes,world wah ha ha"));   # => "hello yes,world"
var_dump(first3words("hello yes world wah ha ha"));   # => "hello yes world"
var_dump(first3words("hello yes world"));  # => "hello yes world"
var_dump(first3words("hello yes world.")); # => "hello yes world"
var_dump(first3words("hello yes"));  # => "hello yes"
var_dump(first3words("hello"));  # => "hello"
var_dump(first3words("a")); # => "a"
var_dump(first3words(""));  # => ""
動靜能量
A: 

what about

chunk_split($str,20);

Entry in the PHP Manual

fly.floh