Match String and Get Variable PHP

折月煮酒 提交于 2019-12-12 04:58:17

问题


I would like to be able to use this string to pull off a certain piece of data from a database '{my-id-1}' so basically if this is found in the text '{my-id-*}' then get the id (eg. if {is-id-1} then ID is 1) and then I can run some code with that ID.

So I've got it so I can get the ID from the braces, but I'm not sure how to replace that within the text.

<?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;
?>

The Array for the matches outputs:

Array ( 
  [0] => Array ( 
    [0] => {is-id-1} 
    [1] => {is-id-2} 
  ) 
  [1] => Array ( 
    [0] => 1 
    [1] => 2 
  ) 
)

I'm stuck now and not sure how to can process each of the braces. Can anyone give me a hand?

Thanks.


回答1:


I am not sure I understood well what you want, but I think this is it:

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


来源:https://stackoverflow.com/questions/16710286/match-string-and-get-variable-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!