How to get the first number from a string in PHP

1 Answer

0 votes
function getFirstNumbers($s) {
    preg_match('/\d+/', $s, $matches);
    
    if (!empty($matches)) {
        return (int)$matches[0];
    }
    
    return -1;
}

$str = "ZQ14876Fu2357-X18Y";

echo getFirstNumbers($str);



/*
run:
   
14876
   
*/

 



answered Oct 22, 2024 by avibootz

Related questions

1 answer 96 views
5 answers 431 views
1 answer 127 views
1 answer 171 views
1 answer 176 views
...