匹配字符串并获取变量PHP

匹配字符串并获取变量PHP,php,preg-match,Php,Preg Match,我希望能够使用这个字符串从数据库{my-id-1}中提取某个数据段,因此基本上,如果在文本{my id-*}中找到该数据段,则获取该id(例如,如果{is-id-1},则id为1),然后我可以使用该id运行一些代码 所以我得到了它,所以我可以从大括号中得到ID,但我不确定如何在文本中替换它 <?php $text = "test 1 dfhjsdh sdjkfhksdhfkj skjh {is-id-1} sdfhskdfh sdfsdjfhksd fjksdfhksd {is-id-2}

我希望能够使用这个字符串从数据库{my-id-1}中提取某个数据段,因此基本上,如果在文本{my id-*}中找到该数据段,则获取该id(例如,如果{is-id-1},则id为1),然后我可以使用该id运行一些代码

所以我得到了它,所以我可以从大括号中得到ID,但我不确定如何在文本中替换它

<?php
$text = "test 1 dfhjsdh sdjkfhksdhfkj skjh {is-id-1} sdfhskdfh sdfsdjfhksd fjksdfhksd {is-id-2}";
preg_match_all('/{is-id-+(.*?)}/',$text, $matches);
print_r ($matches);

$replacewiththis = "this has been replaced, it was id: " . $idhere;
$text = preg_replace('/{is-id-+(.*?)}/', $replacewiththis, $text);

echo $text;
?>
我现在被卡住了,不知道如何处理每个牙套。谁能帮我一把吗


谢谢。

我不太清楚您想要什么,但我想这就是:

foreach($matches[1] as $match){
  $replacewiththis = "this has been replaced, it was id: $match";
  $text=str_replace('{is-id-'.$match.'}', $replacewiththis, $text);
}
echo $text;

返回的
$matches
是一个由2个数组组成的数组,第一个是匹配项,第二个是所需的
ID
。(因此,
$matches[0][0]=>1,$matches[0][1]=>2
)该函数返回所有匹配项,而不仅仅是一个,因此您需要一个循环。谢谢!就是这样!
foreach($matches[1] as $match){
  $replacewiththis = "this has been replaced, it was id: $match";
  $text=str_replace('{is-id-'.$match.'}', $replacewiththis, $text);
}
echo $text;