Advertisement
AlexWebDevelop

Untitled

May 25th, 2022
826
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 0.68 KB | None | 0 0
  1. function getWords(string $string, int $words): string
  2. {
  3.     $ret = '';
  4.    
  5.     $insideTag = FALSE;
  6.     $wCount = 0;
  7.     $lastChar = NULL;
  8.    
  9.     for ($i = 0; ($i < \mb_strlen($string)) && ($wCount < $words); $i++)
  10.     {
  11.         $char = \mb_substr($string, $i, 1);
  12.        
  13.         if ($char === '<')
  14.         {
  15.             $insideTag = TRUE;
  16.            
  17.             if (\ctype_alnum($lastChar))
  18.             {
  19.                 $wCount++;
  20.             }
  21.         }
  22.         else if ($char === '>')
  23.         {
  24.             $insideTag = FALSE;
  25.         }
  26.         else if (!\ctype_alnum($char))
  27.         {
  28.             if (!$insideTag && \ctype_alnum($lastChar))
  29.             {
  30.                 $wCount++;
  31.             }
  32.         }
  33.        
  34.         $lastChar = $char;
  35.        
  36.         if (!$insideTag && ($char !== '>'))
  37.         {
  38.             $ret .= $char;
  39.         }
  40.     }
  41.    
  42.     $ret = trim($ret);
  43.    
  44.     return $ret;
  45. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement