Frequency of a substring in a string | Simple PHP program to count occurrences of pat in txt . ; A loop to slide pat [ ] one by one ; For current index i , check for pattern match ; if pat [ 0. . . M - 1 ] = txt [ i , i + 1 , ... i + M - 1 ] ; Driver Code
< ? php function countFreq ( $ pat , $ txt ) { $ M = strlen ( $ pat ) ; $ N = strlen ( $ txt ) ; $ res = 0 ; for ( $ i = 0 ; $ i <= $ N - $ M ; $ i ++ ) { for ( $ j = 0 ; $ j < $ M ; $ j ++ ) if ( $ txt [ $ i + $ j ] != $ pat [ $ j ] ) break ; if ( $ j == $ M ) { $ res ++ ; $ j = 0 ; } } return $ res ; } $ txt = " dhimanman " ; $ pat = " man " ; echo countFreq ( $ pat , $ txt ) ;