Count words in a given string | PHP program to count no of words from given input string ; returns number of words in str ; word count ; Scan all characters one by one ; If next character is a separator , set the state as OUT ; If next character is not a word separator and state is OUT , then set the state as IN and increment word count ; Move to next character ; Driver Code
< ? php $ OUT = 0 ; $ IN = 1 ; function countWords ( $ str ) { global $ OUT , $ IN ; $ state = $ OUT ; $ wc = 0 ; $ i = 0 ; while ( $ i < strlen ( $ str ) ) { if ( $ str [ $ i ] == " ▁ " $ str [ $ i ] == " STRNEWLINE " $ str [ $ i ] == " TABSYMBOL " ) $ state = $ OUT ; else if ( $ state == $ OUT ) { $ state = $ IN ; ++ $ wc ; } ++ $ i ; } return $ wc ; } $ str = " One ▁ two TABSYMBOL TABSYMBOL three STRNEWLINE ▁ four TABSYMBOL five ▁ " ; echo " No ▁ of ▁ words ▁ : ▁ " . countWords ( $ str ) ; ? >