I have a code snippet written in PHP that pulls a block of text from a database and sends it out to a widget on a webpage. The original block of text can be a lengthy artic
Based on @Justin Poliey's regex:
// Trim very long text to 120 characters. Add an ellipsis if the text is trimmed.
if(strlen($very_long_text) > 120) {
$matches = array();
preg_match("/^(.{1,120})[\s]/i", $very_long_text, $matches);
$trimmed_text = $matches[0]. '...';
}
Added IF/ELSEIF statements to the code from Dave and AmalMurali for handling strings without spaces
if ((strpos($string, ' ') !== false) && (strlen($string) > 200)) {
$WidgetText = substr($string, 0, strrpos(substr($string, 0, 200), ' '));
}
elseif (strlen($string) > 200) {
$WidgetText = substr($string, 0, 200);
}
I believe this is the easiest way to do it:
$lines = explode('♦♣♠',wordwrap($string, $length, '♦♣♠'));
$newstring = $lines[0] . ' • • •';
I'm using the special characters to split the text and cut it.
$WidgetText = substr($string, 0, strrpos(substr($string, 0, 200), ' '));
And there you have it — a reliable method of truncating any string to the nearest whole word, while staying under the maximum string length.
I've tried the other examples above and they did not produce the desired results.
$shorttext = preg_replace('/^([\s\S]{1,200})[\s]+?[\s\S]+/', '$1', $fulltext);
Description:
^
- start from beginning of string([\s\S]{1,200})
- get from 1 to 200 of any character[\s]+?
- not include spaces at the end of short text so we can avoid word ...
instead of word...
[\s\S]+
- match all other contentTests:
or
few other r
orrrr
exactly 200 characters.r
orrrrr
excluded.Enjoy.
Here you go:
function neat_trim($str, $n, $delim='…') {
$len = strlen($str);
if ($len > $n) {
preg_match('/(.{' . $n . '}.*?)\b/', $str, $matches);
return rtrim($matches[1]) . $delim;
}
else {
return $str;
}
}