查找字符串中任何数字首次出现的位置

问题描述 投票:9回答:5

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

我在网上找到的代码无效:

function my_offset($text){
    preg_match('/^[^\-]*-\D*/', $text, $m);
    return strlen($m[0]);
}
echo my_offset('[HorribleSubs] Bleach - 311 [720p].mkv');
php regex string character find-occurrences
5个回答
15
投票
function my_ofset($text){
    preg_match('/^\D*(?=\d)/', $text, $m);
    return isset($m[0]) ? strlen($m[0]) : false;
}

应为此工作。原始代码要求在第一个数字之前输入-,也许是问题所在?


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);
}

11
投票

内置的PHP函数strcspn()的用法与Stanislav Shabalin的答案相同:

strcspn()

示例:

strcspn( $str , '0123456789' )

HTH


0
投票

我可以做正则表达式,但是我必须进入改变状态记住我编码后的功能。

这是您可以使用的简单PHP函数...

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

0
投票

问题

查找字符串中第一个出现的数字

解决方案

这里是JavaScript中的非正则表达式解决方案

function findFirstNum($myString) {

    $slength = strlen($myString);

    for ($index = 0;  $index < $slength; $index++)
    {
        $char = substr($myString, $index, 1);

        if (is_numeric($char))
        {
            return $index;
        }
    }

    return 0;  //no numbers found
}

示例输入

var findFirstNum = function(str) {
    let i = 0;
    let result = "";
    let value;
    while (i<str.length) {
      if(!isNaN(parseInt(str[i]))) {
        if (str[i-1] === "-") {
          result = "-";
        }
        while (!isNaN(parseInt(str[i])) && i<str.length) {
          result = result + str[i];
          i++;
        }
        break;
      }
      i++;
    }
    return parseInt(result);  
};

输出

findFirstNum("words and -987 555");
© www.soinside.com 2019 - 2024. All rights reserved.