0

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
  • The returned $matches is an array of 2 arrays, the first one is the matches and the second one is the ID you want. (so $matches[0][0] => 1 , $matches[0][1] => 2) The function returns all the matches , not just one , so you'll need a loop. Commented May 23, 2013 at 9:33

1 Answer 1

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;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.