3v4l.org

run code in 300+ PHP versions simultaneously
<?php $strings = [ 'StackOverFlow is the best site ever', // 22 ----------------^ 'http://stackoverflow.com is the best site ever', // 22 ----------------^ 'Short string', // no ellipsis needed ^ 'pneumonoultramicroscopicsilicovolcanoconiosis', // breakpoint between ^ letters ]; function word_wrap_custom($string, $limit) { $oneWord = explode(' ', $string); if(count($oneWord) < 2 ) return $oneWord[0]; $string = substr($string, 0, $limit + 2); $endchar = substr($string, $limit, $limit + 1); $postendchar = substr($string, $limit + 1, $limit + 2); $arrAccetpEndChar = array(' ', '!', '?', ',', '.', ';', ':'); if(in_array($postendchar, $arrAccetpEndChar) || in_array($endchar, $arrAccetpEndChar)) { return $string; } else { return preg_replace('/[A-Za-z0-9]+$/', '', $string); } } foreach ($strings as $string) { var_export( word_wrap_custom($string, 22) ); echo "\n"; }

preferences:
30.21 ms | 408 KiB | 5 Q