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

Random string generator...

Random string generator. Optionally, you can give it a desired string length. function rnd_string($len = 24) { $str = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; $str...

Delete file function...

If file exists then delete the file. function delFile( $file_name ) { if ( file_exists( $file_name ) ) // Does '$file_name' exist { unlink( $file_name ); return true; } ...

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 ...

File size calculator...

File size calculator function return file size format into kb, mb or gb. function file_size($size, $out = 'kb', $precision = 2) { switch ($out) { case 'kb': return round($...