文字列に html タグ、 、および複数のスペースが含まれていると、問題が発生する可能性があります。すべてを処理するために私が使用するものは次のとおりです。
function LimitText($string,$limit,$remove_html=0){
if ($remove_html==1){$string=strip_tags($string);}
$newstring = preg_replace("/(?:\s| )+/"," ",$string, -1); // replace   with space
$newstring = preg_replace(array('/\s{2,}/','/[\t\n]/'),' ',$newstring); // replace duplicate spaces
if (strlen($newstring)<=$limit) { return $newstring; } // ensure length is more than $limit
$newstring = substr($newstring,0,strrpos(substr($newstring,0,$limit),' '));
return $newstring;
}
利用方法:
$string = 'My wife is jealous of stackoverflow';
echo LimitText($string,20);
// My wife is jealous
html での使用法:
$string = '<div><p>My wife is jealous of stackoverflow</p></div>';
echo LimitText($string,20,1);
// My wife is jealous