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

How to created mixed arguments function...

This way useful for create mixed arguments function. function foo() { $args = func_get_args(); print_r($args); }   foo(1, 1256, 6, 17); //mixed ...   -------------------Out-...

Create directory function...

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

Detect leap year...

Detect leap year for gregorian and shamsi date. function gLeapYear($year) { if (($year % 4 == 0) and (($year % 100 != 0) or ($year % 400 == 0))) return true; else return ...

Delete or Remove all files and folders in a directory‎...

If you want to delete everything from folder (including subfolders) use this function. function removeDir( $dir ) { if ( is_dir( $dir ) ) { $objects = scandir( $dir ); foreach ( $o...