Count of occurrences of a "1(0 + ) 1" pattern in a string | Returns count of occurrences of "1(0 + ) 1" ; $count = 0 ; Initialize result ; Check if encountered '1' forms a valid pattern as specified ; if 1 encountered for first time set oneSeen to 1 ; Check if there is any other character other than '0' or '1' . If so then set oneSeen to 0 to search again for new pattern ; Driver Code
< ? php function countPattern ( $ str ) { $ len = strlen ( $ str ) ; $ oneSeen = 0 ; for ( $ i = 0 ; $ i < $ len ; $ i ++ ) { if ( $ str [ $ i ] == '1' && $ oneSeen == 1 ) if ( $ str [ $ i - 1 ] == '0' ) $ count ++ ; if ( $ str [ $ i ] == '1' && $ oneSeen == 0 ) $ oneSeen = 1 ; if ( $ str [ $ i ] != '0' && $ str [ $ i ] != '1' ) $ oneSeen = 0 ; } return $ count ; } $ str = "100001abc101" ; echo countPattern ( $ str ) ; ? >