Find the position of the first occurrence of any n

2020-03-13 04:48发布

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

5条回答
男人必须洒脱
2楼-- · 2020-03-13 05:24
function my_ofset($text){
    preg_match('/^\D*(?=\d)/', $text, $m);
    return isset($m[0]) ? strlen($m[0]) : false;
}

should work for this. The original code required a - to come before the first number, perhaps that was the problem?

查看更多
淡お忘
3楼-- · 2020-03-13 05:24
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);
}
查看更多
劫难
4楼-- · 2020-03-13 05:29

The built-in PHP function strcspn() will do the same as the function in Stanislav Shabalin's answer when used like so:

strcspn( $str , '0123456789' )

Examples:

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

HTH

查看更多
你好瞎i
5楼-- · 2020-03-13 05:34

I can do regular expressions but I have to go into an altered state to remember what it does after I've coded it.

Here is a simple PHP function you can use...

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
}
查看更多
闹够了就滚
6楼-- · 2020-03-13 05:35

Problem

Find the first occurring number in a string

Solution

Here is a non regex solution in javascript

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

Example Input

findFirstNum("words and -987 555");

Output

-987
查看更多
登录 后发表回答