I'm trying to cut a chunk of text down to around 30 characters. If it's shorter, I want the previous string. On top of that, it has forum-style code in. I want to strip out everything between square-brackets ([]
)
I'm using a pair of functions to do that. forum_extract
is what I call.
function forum_extract($text) {
return str_replace("\n",'<br />', limit_text(preg_replace('/\[[^\]]+\]/', '', $text), 30));
}
function limit_text($text, $limit) {
if (strlen($text) <= $limit)
return $text;
$words = str_word_count($text, 2);
$pos = array_keys($words);
return substr($text, 0, $pos[$limit]) . '...';
}
The problem comes in limit_text
when the provided $text
is shorter than the limit. All I get back is a "...".
For that to happen, it must have passed the guard-clause in limit_text
. But how?
Here is a literal that gets passed into limit_text
but comes out as "...":
Friend of ours paid 150€ the other day from Malaga. Spread across 4 people it didn't seem to bad, given it was a 8+ hour day for the driver, petrol etc.