php – How can i get remaining part of string after numeric digits found-ThrowExceptions

Exception or error:

How can i get remaining part of string after numeric digits found.

ex.1) hello12cool4here

output should be: 2cool4here

ex.2) hel3lo12cool4here

output should be: lo12cool4here

How to solve:

With regexps:

preg_match('/^\D*\d(.*)/', 'hello12cool4here', $matches);
echo($matches[1]);    // 2cool4here
preg_match('/^\D*\d(.*)/', 'hel3lo12cool4here', $matches);
echo($matches[1]);    // lo12cool4here
preg_match('/^\D*\d(.*)/', '42lo12cool4here', $matches);
echo($matches[1]);    // 2lo12cool4here

Answer´╝Ü

You could loop over all the characters and test if they are numeric, return when first is found:

$str='hello12cool4here';

for( $i=0; $i< strlen( $str ); $i++ ){
    if( is_numeric( substr($str,$i,1) ) )exit( substr( $str, $i+1 ) );
}

Or putting that into a function:

function findremainder( $str ){
    for( $i=0; $i< strlen( $str ); $i++ ){
        if( is_numeric( substr($str,$i,1) ) )return( substr( $str, $i+1 ) );
    }
    return $str;
}


echo findremainder( $str );

Leave a Reply

Your email address will not be published. Required fields are marked *