2012-07-09 53 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;