Longest Common Substring in an Array of Strings | function to find the stem ( longest common substring ) from the string array ; Determine size of the array ; Take first word from array as reference ; generating all possible substrings of our reference string arr [ 0 ] i . e s ; Check if the generated stem is common to all words ; If current substring is present in all strings and its length is greater than current result ; Driver Code ; Function call
< ? php function findstem ( $ arr ) { $ n = count ( $ arr ) ; $ s = $ arr [ 0 ] ; $ len = strlen ( $ s ) ; $ res = " " ; for ( $ i = 0 ; $ i < $ len ; $ i ++ ) { for ( $ j = $ i + 1 ; $ j <= $ len ; $ j ++ ) { $ stem = substr ( $ s , $ i , $ j - $ i ) ; $ k = 1 ; for ( $ k = 1 ; $ k < $ n ; $ k ++ ) if ( ! strpos ( $ arr [ $ k ] , $ stem ) ) break ; if ( $ k <= $ n && strlen ( $ res ) < strlen ( $ stem ) ) $ res = $ stem ; } } return $ res ; } $ arr = array ( " grace " , " graceful " , " disgraceful " , " gracefully " ) ; $ stems = findstem ( $ arr ) ; print ( $ stems ) ; ? >