Wednesday 26 August 2020

PHP Program Longest Word from the string

PHP Program Longest Word from the string

 Create PHP function LongestWord(sen) take the sen parameter being passed and return the largest word in the string.

If there are two or more words that are the same length, return the first word from the string with that length. 

Ignore punctuation and assume sen will not be empty.




Solution: 


function LongestWord($sen) {
    $return = '';

    //Convert string into Array
    $strArrayList = explode(' ', $sen);
    $finalArray = array();

    ///////Filter the words///////////
    foreach($strArrayList as $str){
        $str = preg_replace("#[[:punct:]]#", "", $str);
        $finalArray[] = $str;
    }
    ///////Filter the words///////////
    
    /////////// Get the First word  from the string with that length////////
    foreach($finalArray as $word){
        if(strlen($word)> strlen($return)){
        $return = $word;
        }
    }
    /////////// Get the First word  from the string with that length////////
    
    
    return $return;

}