匹配字符串并获取变量PHP

2022-03-29 00:00:00 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}";
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;
?>

匹配输出的数组:

Array ( 
  [0] => Array ( 
    [0] => {is-id-1} 
    [1] => {is-id-2} 
  ) 
  [1] => Array ( 
    [0] => 1 
    [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;

相关文章