How can I truncate a string to the first 20 words in PHP?
function limit_text($text, $limit) {
if (str_word_count($text, 0) > $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 that will be truncated by the', 5);
Outputs:
Hello here is a long ...
Change the number 3
to the number 20
below to get the first 20 words, or pass it as parameter. The following demonstrates how to get the first 3 words: (so change the 3
to 20
to change the default value):
function first3words($s, $limit=3) {
return preg_replace('/((\w+\W*){'.($limit-1).'}(\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("")); # => ""
To Nearest Space
Truncates to nearest preceding space of target character. Demo
-
$str
The string to be truncated -
$chars
The amount of characters to be stripped, can be overridden by$to_space
-
$to_space
boolean
for whether or not to truncate from space near$chars
limit
Function
function truncateString($str, $chars, $to_space, $replacement="...") {
if($chars > strlen($str)) return $str;
$str = substr($str, 0, $chars);
$space_pos = strrpos($str, " ");
if($to_space && $space_pos >= 0)
$str = substr($str, 0, strrpos($str, " "));
return($str . $replacement);
}
Sample
<?php
$str = "this is a string that is just some text for you to test with";
print(truncateString($str, 20, false) . "\n");
print(truncateString($str, 22, false) . "\n");
print(truncateString($str, 24, true) . "\n");
print(truncateString($str, 26, true, " :)") . "\n");
print(truncateString($str, 28, true, "--") . "\n");
?>
Output
this is a string tha...
this is a string that ...
this is a string that...
this is a string that is :)
this is a string that is--
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));