匹配字符串并获取变量PHP [英] Match String and Get Variable PHP

查看:16
本文介绍了匹配字符串并获取变量PHP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够使用此字符串从数据库‘{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;

这篇关于匹配字符串并获取变量PHP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆