How to add a "..." after a particular word/character limit in PHP?
You might simply do a preg_split
on spaces, then join the array back to a string, with a limit number, if you wish:
$str = "absv shss xcnx shss hshhs shhsw shshs hsnna hssnnss hssns snnss nnshs sjjjjsjsj nsnnnsns jjsnss snsnns nsnns";$arr = preg_split('/(\s)/m', $str);$limit = 8;$title = '';foreach ($arr as $key => $value) { if ($key < $limit) { $title .= $value . " "; } else { $title .= "..."; break; }}var_dump($title);
Output
string(47) "absv shss xcnx shss hshhs shhsw shshs hsnna ..."
You might also add an if
statement, in case the number of words was less than your desired limit, so that to just break the loop, maybe something similar to:
$str = "absv shss xcnx shss hshhs";// $str = "absv shss xcnx shss hshhs shhsw shshs hsnna hssnnss hssns snnss nnshs sjjjjsjsj nsnnnsns jjsnss snsnns nsnns";$arr = preg_split('/(\s)/m', $str);$limit = 8;$title = '';foreach ($arr as $key => $value) { if (sizeof($arr) < $limit - 1) { $title .= $str . " ..."; break; } if ($key < $limit) { $title .= $value . " "; } else { $title .= "..."; break; }}var_dump($title);
Output
string(29) "absv shss xcnx shss hshhs ..."
Implement
If you wish to implement this code, this might work:
$arr = preg_split('/(\s)/m', get_the_title());$limit = 8; // number of words limit$title = '';foreach ($arr as $key => $value) { if (sizeof($arr) < $limit - 1) { $title .= get_the_title() . " ..."; break; } if ($key < $limit) { $title .= $value . " "; } else { $title .= "..."; break; }}$out = '<div class="case-breaking__content">';$out .= '<p>';$out .= $title;$out .= '</p>';$out .= '</div>';echo $out;
the_title()
echoes the title rather than returning it. If you're performing operations on it then you want to use get_the_title()
.
<div class="case-breaking__content"><p><?php echo strlen(get_the_title()) > 50 ? substr(get_the_title(), 0, 50) . "..." : get_the_title(); ?></p></div>
That being said if you're using WordPress the easiest option is to use the built-in function wp_trim_words()
https://codex.wordpress.org/Function_Reference/wp_trim_words
So in your case
<div class="case-breaking__content"><p><?php echo wp_trim_words( get_the_title(), 8, '...') ?></p></div>