Replace two substrings ( of a string ) with each other | Function to return the resultant string ; Iterate through all positions i ; Current sub - string of length = len ( A ) = len ( B ) ; If current sub - string gets equal to A or B ; Update S after replacing A ; Update S after replacing B ; Return the updated string ; Driver code
< ? php function updateString ( $ S , $ A , $ B ) { $ l = strlen ( $ A ) ; for ( $ i = 0 ; $ i + $ l <= strlen ( $ S ) ; $ i ++ ) { $ curr = substr ( $ S , $ i , $ i + $ l ) ; if ( strcmp ( $ curr , $ A ) == 0 ) { $ new_string = substr ( $ S , 0 , $ i ) . $ B . substr ( $ S , $ i + $ l , strlen ( $ S ) ) ; $ S = $ new_string ; $ i += $ l - 1 ; } else { $ new_string = substr ( $ S , 0 , $ i ) . $ A . substr ( $ S , $ i + $ l , strlen ( $ S ) ) ; $ S = $ new_string ; $ i += $ l - 1 ; } } return $ S ; } $ S = " aab " ; $ A = " aa " ; $ B = " bb " ; echo ( updateString ( $ S , $ A , $ B ) ) ;