Find the position of the first occurrence of any number in string

Gasper picture Gasper · Sep 21, 2011 · Viewed 19k times · Source

Can someone help me with algorithm for finding the position of the first occurrence of any number in a string?

The code I found on the web does not work:

function my_offset($text){
    preg_match('/^[^\-]*-\D*/', $text, $m);
    return strlen($m[0]);
}
echo my_offset('[HorribleSubs] Bleach - 311 [720p].mkv');

Answer

Stanislav Shabalin picture Stanislav Shabalin · Sep 21, 2011
function my_offset($text) {
    preg_match('/\d/', $text, $m, PREG_OFFSET_CAPTURE);
    if (sizeof($m))
        return $m[0][1]; // 24 in your example

    // return anything you need for the case when there's no numbers in the string
    return strlen($text);
}