Minimum characters to be replaced to remove the given substring | function to calculate minimum characters to replace ; mismatch occurs ; if all characters matched , i . e , there is a substring of ' a ' which is same as string ' b ' ; increment i to index m - 1 such that minimum characters are replaced in ' a ' ; Driver Code
< ? php function replace ( $ A , $ B ) { $ n = strlen ( $ A ) ; $ m = strlen ( $ B ) ; $ count = 0 ; for ( $ i = 0 ; $ i < $ n ; $ i ++ ) { for ( $ j = 0 ; $ j < $ m ; $ j ++ ) { if ( $ i + $ j >= $ n ) { break ; } else if ( $ A [ $ i + $ j ] != $ B [ $ j ] ) { break ; } } if ( $ j == $ m ) { $ count ++ ; $ i = $ i + $ m - 1 ; } } return $ count ; } $ str1 = " aaaaaaaa " ; $ str2 = " aaa " ; echo ( replace ( $ str1 , $ str2 ) ) ; ? >