Extract maximum numeric value from a given string | Set 1 ( General approach ) | Utility function to find maximum string ; If both having equal lengths ; Reach first unmatched character / value ; Return string with maximum value ; If different lengths return string with maximum length ; Function to extract the maximum value ; Start traversing the string ; Ignore leading zeroes ; Store numeric value into a string ; Update maximum string ; To handle the case if there is only 0 numeric value ; Return maximum string ; Drivers program
< ? php function maximumNum ( $ curr_num , $ res ) { $ len1 = strlen ( $ curr_num ) ; $ len2 = strlen ( $ res ) ; if ( $ len1 == $ len2 ) { $ i = 0 ; while ( $ curr_num [ $ i ] == $ res [ $ i ] ) $ i ++ ; if ( $ curr_num [ $ i ] < $ res [ $ i ] ) return $ res ; else return $ curr_num ; } return $ len1 < $ len2 ? $ res : $ curr_num ; } function extractMaximum ( $ str ) { $ n = strlen ( $ str ) ; $ curr_num = " " ; $ res = " " ; for ( $ i = 0 ; $ i < $ n ; $ i ++ ) { while ( $ i < $ n && $ str [ $ i ] == '0' ) $ i ++ ; while ( $ i < $ n && $ str [ $ i ] >= '0' && $ str [ $ i ] <= '9' ) { $ curr_num . = $ str [ $ i ] ; $ i ++ ; } if ( $ i == $ n ) break ; if ( strlen ( $ curr_num ) > 0 ) $ i -- ; $ res = maximumNum ( $ curr_num , $ res ) ; $ curr_num = " " ; } if ( strlen ( $ curr_num ) == 0 && strlen ( $ res ) == 0 ) $ res . = '0' ; return maximumNum ( $ curr_num , $ res ) ; } $ str = "100klh564abc365bg " ; echo extractMaximum ( $ str ) ; ? >