Match string and get PHP variable
I would like to be able to use this string to retrieve a specific piece of data from database '{my-id-1}', so basically if found in the text '{my-id- *}' then enter id (for example if {is-id-1} then ID is 1) and then I can run some code with that id.
So I have this, so I can get the ID from the curly braces, but I'm not sure how to replace it in 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;
?>
Array for matched outputs:
Array (
[0] => Array (
[0] => {is-id-1}
[1] => {is-id-2}
)
[1] => Array (
[0] => 1
[1] => 2
)
)
I am stuck now and not sure how to handle each shape. Can someone give me a hand?
Thank.
0
user1380591
source
to share
1 answer
I'm not sure if I understood well what you want, but I think it is:
foreach($matches[1] as $match){
$replacewiththis = "this has been replaced, it was id: $match";
$text=str_replace('{is-id-'.$match.'}', $replacewiththis, $text);
}
echo $text;
+1
CodeBird
source
to share