Trimming a string down
<p>I'm trying to cut a chunk of text down to <em>around</em> 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 (<code>[]</code>)</p>

<p>I'm using a pair of functions to do that. <code>forum_extract</code> is what I call.</p>

<pre><code>function forum_extract($text) {
        return str_replace("\n",'&lt;br /&gt;', limit_text(preg_replace('/\[[^\]]+\]/', '', $text), 30));
}

function limit_text($text, $limit) {
        if (strlen($text) &lt;= $limit)
                return $text;

        $words = str_word_count($text, 2);
        $pos = array_keys($words);
        return substr($text, 0, $pos[$limit]) . '...';
}
</code></pre>

<p>The problem comes in <code>limit_text</code> when the provided <code>$text</code> is shorter than the limit. All I get back is a "...".</p>

<p>For that to happen, it must have passed the guard-clause in <code>limit_text</code>. But how?</p>

<p>Here is a literal that gets passed into <code>limit_text</code> but comes out as "...":</p>

<pre><code>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.
</code></pre>
