Prepare the strings to be limited with a custom php function
<p>I need a little bit of help.
I have a function that limits text using the php <code>wordwrap()</code>.
The problem is that I have noticed it does not limit the text as it should, sometimes cutting to soon.
I think the problem lies with getting the strings ready for limiting them which I do like this:</p>

<pre><code>  function mytrim($mytrim){
        $mytrim = strip_tags($mytrim); 
        $mytrim = preg_replace('/\s+/',' ',$mytrim);
        $mytrim = trim($mytrim);
        $mytrim = ucfirst($mytrim);
        $mytrim = str_replace(',', ', ', $mytrim); 
        $mytrim = str_replace('_', ', ', $mytrim);

        $punctuation = substr($mytrim, -1); 
        $punct = array(".","?","!");
        if(!in_array($punctuation, $punct)){ $mytrim .= '.'; } 

        return $mytrim;
    }
</code></pre>

<ol>
<li>I strip tags;</li>
<li>I remove multiple whitespaces;</li>
<li>I trim it and do some other stuff.</li>
</ol>

<p><strong>The problem is I still get whitespaces after all this.</strong></p>

<p>Here is the function I use for limiting the text:</p>

<pre><code>function limit_text($text, $length){ // Limit Text
// Truncate the string without breaking words
    list($wrapped) = explode("\n", wordwrap($text, $length));
// Get the span of text occurring after the wrapped string
$remainder = substr($text, strlen($wrapped));
// Add the "to be continued" to $wrapped
    $wrapped = rtrim($wrapped,',.;:- _!$&amp;#'); 
$wrapped .= ' ... ';
// Now, grab all of the &lt;span class="highlight"&gt;&lt;/span&gt; tags in the $remainder
preg_match_all( '#&lt;span class="highlighted"&gt;[^&lt;]+&lt;/span&gt;#i', $remainder, $matches);
// Add the &lt;span&gt; tags to the end of the string, separated by a comma, if present
$wrapped .= implode( ', ', $matches[0]);
return $wrapped;
}
</code></pre>
