How to find the largest and the smallest word in a string with PHP

2 Answers

0 votes
$s = "php python c++ c c# java";
 
$words = explode(" ", $s);

$max = "";
$min = $s;
 
foreach ($words as &$w) 
{
    if (strlen($w) > strlen($max)) $max = $w;  
    if (strlen($w) < strlen($min)) $min = $w;  
}   

echo "The largest word is: " . $max . "<br />";
echo "The smallest word is: " . $min . "<br />";


/*
run:
   
The largest word is: python
The smallest word is: c
    
*/

 



answered Mar 23, 2017 by avibootz
0 votes
declare(strict_types=1);

/**
 * Finds the largest and smallest words in a given string.
 * 
 * @param string $text The input string containing words.
 * @return array{0: string, 1: string} An array containing [largest_word, smallest_word].
 */
function findLargestAndSmallestWords(string $text): array {
    $trimmed = trim($text);
    if ($trimmed === '') {
        return ['', ''];
    }

    // Split the string into words by arbitrary whitespace using a regular expression
    $words = preg_split('/\s+/', $trimmed);
    if ($words === false || empty($words)) {
        return ['', ''];
    }

    $largest = $words[0];
    $smallest = $words[0];

    // Iterate through words to find extrema based on length (using mb_strlen for UTF-8 safety)
    foreach ($words as $word) {
        if (mb_strlen($word) > mb_strlen($largest)) {
            $largest = $word;
        }
        if (mb_strlen($word) < mb_strlen($smallest)) {
            $smallest = $word;
        }
    }

    return [$largest, $smallest];
}

// Main execution
$s = "PHP is a popular general-purpose scripting language especially suited to web development";

// Use modern PHP list destructuring (similar to Go and Ruby multi-value assignment)
[$largest, $smallest] = findLargestAndSmallestWords($s);

echo "Largest word:  {$largest}\n";
echo "Smallest word: {$smallest}\n";


/*
run:

Largest word:  general-purpose
Smallest word: a

*/

 



answered 1 day ago by avibootz
...