Short a string without cutting words

I develop this function to short the string without cutting the words. As we now that PHP’s substr() function only provide the part of the string, substr() function provide the string between the two parameters, start from and end to.

So I need a function that provide the string arround the given starting from and end to range. Below given function provide the arround complete word from the string. This function check the nearest space into the string and provide the nearest word without cutting. If you guys have a better alternative then please feel free to share the codes in the comment section.

function _substr( $str, $start, $end ) {

    $left_str = substr($str, $start, $end);
    $right_str = substr($str, $end, ($end + 20));

    $str_lpart = explode(" ", $left_str);
    $str_rpart = explode(" ", $right_str);

    krsort($str_lpart);
    $total_l = count($str_lpart) - 1;

    $str_lval = strlen($str_lpart[$total_l]);
    $str_rval = strlen($str_rpart[0]);

    if( $str_lval < $str_rval ) $new_str = substr( $str, $start, ($end - $str_lval) );
    else $new_str = substr( $str, $start, ($end + $str_rval) );

    return $new_str;

}

 

Posted by Jogesh Sharma

Jogesh Sharma is a web developer and blogger who loves all the things design and the technology, He love all the things having to do with PHP, WordPress, Joomla, Magento, Durpal, Codeigniter, jQuery, HTML5 etc. He is the author of this blog.