在字符串中找到第一个出现的任何数字的位置(php)

Gas*_*per 9 php regex string character find-occurrences

有人可以帮助我找到字符串中任何数字首次出现位置的算法吗?

代码我在网上找到它并且不起作用:

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

Sta*_*lin 20

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);
}
Run Code Online (Sandbox Code Playgroud)

  • 更有意义.我(和RegexBuddy)不知道'PREG_OFFSET_CAPTURE` :) (2认同)

Tim*_*ker 15

function my_ofset($text){
    preg_match('/^\D*(?=\d)/', $text, $m);
    return isset($m[0]) ? strlen($m[0]) : false;
}
Run Code Online (Sandbox Code Playgroud)

应该为此工作.原始代码需要-在第一个数字之前出现,也许这就是问题所在?


小智 11

内置的PHP函数strcspn()将与Stanislav Shabalin的答案中的函数相同,如下所示:

strcspn( $str , '0123456789' )
Run Code Online (Sandbox Code Playgroud)

例子:

echo strcspn( 'That will be $2.95 with a coupon.' , '0123456789' ); // 14
echo strcspn( '12 people said yes'                , '0123456789' ); // 0
echo strcspn( 'You are number one!'               , '0123456789' ); // 19
Run Code Online (Sandbox Code Playgroud)

HTH

  • 我敢打赌这比任何正则表达式解决方案快 20 倍 (3认同)