Php 从特定模式获取变量
我需要将每对花括号之间的数字保存为变量Php 从特定模式获取变量,php,variables,preg-replace,pattern-matching,Php,Variables,Preg Replace,Pattern Matching,我需要将每对花括号之间的数字保存为变量 {2343} -> $number echo $number; Output = 2343 我不知道怎么做'->'部分 我发现了一个类似的函数,但它只是删除了花括号,其他什么都不做 preg_replace('#{([0-9]+)}#','$1', $string); 有什么功能我可以使用吗?您可能希望与捕获一起使用: $subject = "{2343}"; $pattern = '/\{(\d+)\}/'; preg_match($patte
{2343} -> $number
echo $number;
Output = 2343
我不知道怎么做'->'部分
我发现了一个类似的函数,但它只是删除了花括号,其他什么都不做
preg_replace('#{([0-9]+)}#','$1', $string);
有什么功能我可以使用吗?您可能希望与捕获一起使用:
$subject = "{2343}";
$pattern = '/\{(\d+)\}/';
preg_match($pattern, $subject, $matches);
print_r($matches);
输出:
Array
(
[0] => {2343}
[1] => 2343
)
Array
(
[0] => Array
(
[0] => {123}
[1] => {456}
)
[1] => Array
(
[0] => 123
[1] => 456
)
)
如果找到,$matches
数组将在索引1处包含结果,因此:
if(!empty($matches) && isset($matches[1)){
$number = $matches[1];
}
如果输入字符串可以包含多个数字,请使用preg_match_all:
$subject = "{123} {456}";
$pattern = '/\{(\d+)\}/';
preg_match_all($pattern, $subject, $matches);
print_r($matches);
输出:
Array
(
[0] => {2343}
[1] => 2343
)
Array
(
[0] => Array
(
[0] => {123}
[1] => {456}
)
[1] => Array
(
[0] => 123
[1] => 456
)
)
这是家庭作业吗?恐怕有点像,特别是在我过去在黑板上看到的情况下。很抱歉给你带来了困惑。