2012-07-09 62 views
0

我需要將每對大括號之間的數字保存爲一個變量。從某個模式獲取變量

{2343} -> $number 
echo $number; 
Output = 2343 

我不知道怎麼做' - >'部分。

我發現了一個類似的函數,但它只是刪除大括號而不做其他任何事情。

preg_replace('#{([0-9]+)}#','$1', $string); 

有什麼功能可以使用嗎?

+0

這是一個家庭作業? – 2012-07-09 08:53:06

+0

不,我正在做點什麼。 – gyogyo0101 2012-07-09 09:05:56

+0

恐怕它稍微有點兒了,特別是在我以前在這個板子上看到的東西之後。對困惑感到抱歉。 – 2012-07-09 09:09:13

回答

1

您可能需要使用preg_match與捕獲:

$subject = "{2343}"; 
$pattern = '/\{(\d+)\}/'; 
preg_match($pattern, $subject, $matches); 
print_r($matches); 

輸出:

Array 
(
    [0] => {2343} 
    [1] => 2343 
) 

如果發現$matches數組將包含在索引1的結果,所以:

if(!empty($matches) && isset($matches[1)){ 
    $number = $matches[1]; 
} 

如果你的輸入字符串可以包含很多數字,那麼使用preg_mat ch_all:

$subject = "{123} {456}"; 
$pattern = '/\{(\d+)\}/'; 
preg_match_all($pattern, $subject, $matches); 
print_r($matches); 

輸出:

Array 
(
    [0] => Array 
     (
      [0] => {123} 
      [1] => {456} 
     ) 

    [1] => Array 
     (
      [0] => 123 
      [1] => 456 
     ) 
) 
0
$string = '{1234}'; 
preg_replace('#{([0-9]+)}#e','$number = $1;', $string); 
echo $number;