Get first number in a string after the first occurrence of identifier

前端 未结 3 526
猫巷女王i
猫巷女王i 2021-01-17 04:19

I\'m working on a function that gets a string like this:

identifier 20 j. - cat: text text text aaaa ffffdd ..... cccc 60\' - text, 2008

and

相关标签:
3条回答
  • 2021-01-17 04:53

    You can use a regular expression for this:

    $matches = array();
    preg_match('/identifier\s*(\d+)/', $string, $matches);
    var_dump($matches);
    

    \s* is whitespace. (\d+) matches a number.

    You can wrap it in a function:

    function matchIdentifier($string) {
        $matches = array();
        if (!preg_match('/identifier\s*(\d+)/', $string, $matches)) {
            return null;
        }
        return $matches[1];
    }
    
    0 讨论(0)
  • 2021-01-17 04:55

    You can get the match itslef without capturing subgroups using \K operator and ^ anchor to match the word only at the beginning of the string:

    $re = "/^identifier \\K\\d+/"; 
    $str = "identifier 20 j. - cat: text text text aaaa ffffdd ..... cccc 60' - text, 2008"; 
    preg_match($re, $str, $matches);
    echo $matches[0];
    

    Demo is here.

    Sample program is available here (PHP v5.5.18).

    0 讨论(0)
  • 2021-01-17 04:59
    $string = "identifier 20 j. - cat: text text text aaaa ffffdd ..... cccc 60' - text, 2008";
    $tokens = explode(' ', $string);
    $token2 = $tokens[1];
    if(is_numeric($token2))
    {
        $value = (int) $token2;
    }
    else
    {
        $value = NULL;
    }
    
    0 讨论(0)
提交回复
热议问题