PHP subwords() Function

Function subwords, gets words by max num.

/**
 * Get words from string...
 * @param string $str: String of words
 * @param integer $max: Maximum words
 * @param char $char: is Delimiter
 * @param string $end: Apend string if string will be cutted
 */
function subwords( $str, $max = 24, $char = ' ', $end = '...' ) {
    $str = trim( $str ) ;
    $str = $str . $char ;
    $len = strlen( $str ) ;
    $words = '' ;
    $w = '' ;
    $c = 0 ;
    for ( $i = 0; $i < $len; $i++ )
        if ( $str[$i] != $char )
            $w = $w . $str[$i] ;
        else
            if ( ( $w != $char ) and ( $w != '' ) ) {
                $words .= $w . $char ;
                $c++ ;
                if ( $c >= $max ) {
                    break ;
                }
                $w = '' ;
            }
    if ( $i+1 >= $len ) {
        $end = '' ;
    }
    return trim( $words ) . $end ;
}
 
echo subwords('Hello World!', 1); //out = 'hello...'

Recommended pages

URL Checker...

This function check if an url is valid or not. function is_valid_url($url) { return preg_match('|^http(s)?://[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(/.*)?$|i', $url); }...

Email Address Checker...

This function check if an e-mail address is valid or not. function valid_email($email) { return preg_match('/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/', $email);...

Human readable file size...

This function return formatting of file sizes in a human readable format. function formatFileSize( $size ) { $file_size = $size; $i = 0;   $name = array( 'byte', 'kB', 'MB', '...

Create directory function...

Create directory if not exists. function createDir( $dir ) { if ( !is_dir( $dir ) ) { mkdir( $dir, 0777 ); return true; } return false; }...