2015-04-12 95 views
0

我的工作是得到这样的字符串函数的第一次出现之后:右后获得第一个数字字符串标识符

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

,并提取数20所以第一个数字字符串中的identifier第一次出现(包括空格)

但是,如果我有一个像这样的字符串:

identifier j. - cat: text text text aaaa dddd ..... cccc 60' - text, 2008 

函数应该返回NUL L,因为在发生identifier(包括空白)后没有数字

请问您能帮我吗? 感谢

+1

请试试你的问题! – Rizier123

回答

2

您可以使用正则表达式是:

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

\s*是空白。 (\d+)匹配一个数字。

您可以在一个功能包装它:

function matchIdentifier($string) { 
    $matches = array(); 
    if (!preg_match('/identifier\s*(\d+)/', $string, $matches)) { 
     return null; 
    } 
    return $matches[1]; 
} 
1
$string = "identifier 20 j. - cat: text text text aaaa dddd ..... cccc 60' - text, 2008"; 
$tokens = explode(' ', $string); 
$token2 = $tokens[1]; 
if(is_numeric($token2)) 
{ 
    $value = (int) $token2; 
} 
else 
{ 
    $value = NULL; 
} 
1

可以使用\K运营商和^锚字只在字符串的开头匹配得而不捕获分组比赛itslef:

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

Demo is here

示例程序是available here(PHP v5.5.18)。

+0

注意:'\ K' [仅支持> 5.2.4](http://php.net/manual/en/regexp.reference.escape.php)。 – Keelan

+0

我在TutorialsPoint上测试,他们有PHP v5.5.18。 –

+0

是的,那很好。我只是添加它作为参考。 – Keelan

相关问题