Advertisement
alexbowey

longest.word

Oct 18th, 2018
115
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.06 KB | None | 0 0
  1. <?php
  2. /*
  3.     Using the PHP language, have the 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.
  4. */
  5. function LongestWord($str) {
  6.  
  7.     if (empty($str))
  8.         throw new Exception("The transmitted data can not be empty \$str");
  9.  
  10.     if (! is_string($str))
  11.         throw new Exception("Missig \$str as string type of data");
  12.        
  13.     $reg = '/[^a-zA-Z]+/';
  14.     $str = preg_replace($reg, " ", $str);
  15.  
  16.     $substr = explode(" ", $str);
  17.    
  18.     // store length of each line into array
  19.     $length = [];
  20.     for ($i=0; $i < count($substr); $i++) {
  21.         array_push($length, strlen($substr[$i]));
  22.     }
  23.    
  24.     // calculate max length of among lines
  25.     $max = $length[0];
  26.     $loc = 0;
  27.     for ($j=0; $j < count($length); $j++) {
  28.         if ($max < $length[$j]) {
  29.             $max = $length[$j];
  30.             $loc = $j + 1 - 1;
  31.         }
  32.     }
  33.  
  34.     $finalRes = $substr[$loc];
  35.     return $finalRes;
  36. };
  37.  
  38. LongestWord("to love grey");
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement