2015-04-12 67 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