PHP: reperire la lunghezza dell'ultima parola in una stringa

In questo articolo vedremo come ottenere la lunghezza dell'ultima parola in una stringa con PHP.

PHP di Gabriele Romanato

In questo articolo vedremo come ottenere la lunghezza dell'ultima parola in una stringa con PHP.

Possiamo utilizzare la seguente funzione.


function length_of_last_word($s) {
    if(!is_string($s) || strlen($s) === 0) {
        return 0;
    }
    $limit = 10000;
    if(strlen($s) > $limit) {
        return 0;
    }
    $s = trim($s);
    $parts = preg_split('/\s/', $s);

    if(count($parts) === 0) {
        return 0;
    }
    if(count($parts) === 1) {
        return strlen(trim($parts[0]));
    }
    $values = [];
    foreach($parts as $part) {
        if(!preg_match('/^\s+$/', $part)) {
            $values[] = $part;
        }
    }
    if(count($values) === 0) {
        return 0;
    }
    if(count($values) === 1) {
        return strlen($values[0]);
    }
    $last_word = $values[count($values) - 1];
    return strlen($last_word);
}

Esempio d'uso:


function main() {
    $tests = ['Hello World', '   fly me   to   the moon  ',
             'luffy is still joyboy'];
    foreach($tests as $test) {
        echo $test . ' ' . length_of_last_word($test) . "\n";
    }         
}

main();