Note that there are some explanatory texts on larger screens.

plurals
  1. POTruncate a string in php without cutting words
    primarykey
    data
    text
    <blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/5519890/extract-a-fixed-number-of-chars-from-an-array-just-full-words">Extract a fixed number of chars from an array, just full words</a> </p> </blockquote> <p>I need to truncate strings when they are longer than 20 chars. Words must always stay together, so that this:</p> <p><strong>say hello to my little friend.</strong></p> <p>becomes this:</p> <p><strong>say hello to my...</strong></p> <p>instead of this:</p> <p><strong>say hello to my litt...</strong></p> <p>I set up this function based on a comment in a very <a href="https://stackoverflow.com/questions/79960/how-to-truncate-a-string-in-php-to-the-word-closest-to-a-certain-number-of-chara/80066#comment10194834_80066">old thread</a>. The problem with this regex is that it removes the last word of the sentence (when there are 2 words or more).</p> <pre><code>function gen_string($string,$min=20) { $new = preg_replace('/\s+?(\S+)?$/','',substr($string,0,$min)); if(strlen($new) &lt; strlen($string)) $new .= '&amp;hellip;'; return $new; } </code></pre> <p>Can someone give me a hand with the regex? Thanks!</p> <p><strong>Solution</strong> by <a href="https://stackoverflow.com/users/1018582/alasdair">Alasdair</a> (with a few retouches)</p> <pre><code>function gen_string($string,$max=20) { $tok = strtok($string,' '); $sub = ''; while($tok !== false &amp;&amp; mb_strlen($sub) &lt; $max) { if(strlen($sub) + mb_strlen($tok) &lt;= $max) { $sub .= $tok.' '; } else { break; } $tok = strtok(' '); } $sub = trim($sub); if(mb_strlen($sub) &lt; mb_strlen($string)) $sub .= '&amp;hellip;'; return $sub; } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload