php trim a string

前端 未结 4 818
灰色年华
灰色年华 2020-12-18 16:37

I\'m trying to build a function to trim a string is it\'s too long per my specifications.

Here\'s what I have:

function trim_me($s,$max) 
{
    if (s         


        
4条回答
  •  心在旅途
    2020-12-18 17:14

    I've named the function str_trunc. You can specify strict being TRUE, in which case it will only allow a string of the maximum size and no more, otherwise it will search for the shortest string fitting in the word it was about to finish.

    var_dump(str_trunc('How are you today?', 10)); // string(10) "How are..."
    var_dump(str_trunc('How are you today? ', 10, FALSE)); // string(14) "How are you..."
    
    // Returns a trunctated version of $str up to $max chars, excluding $trunc.
    // $strict = FALSE will allow longer strings to fit the last word.
    function str_trunc($str, $max, $strict = TRUE, $trunc = '...') {
        if ( strlen($str) <= $max ) {
            return $str;
        } else {
            if ($strict) {
                return substr( $str, 0, strrposlimit($str, ' ', 0, $max + 1) ) . $trunc;
            } else {
                return substr( $str, 0, strpos($str, ' ', $max) ) . $trunc;
            }
        }
    }
    
    // Works like strrpos, but allows a limit
    function strrposlimit($haystack, $needle, $offset = 0, $limit = NULL) {
        if ($limit === NULL) {
            return strrpos($haystack, $needle, $offset);
        } else {
            $search = substr($haystack, $offset, $limit);
            return strrpos($search, $needle, 0);
        }
    }
    

提交回复
热议问题