0

I have a little problem in PHP.

$string = "[:string] has [:int] [:string] and [:int] [:string]";

I just wanna modify (probably with str_replace) it with:

$string = "He has 5 apples and 3 bananas";

How could I do that?

(Classic str_replace() will modify all [:int] with the same word,
and is not what I want).

Thank you very much...

1 Answers1

2

You could use the following regex, to capture all groups to replace and then iterate over it.

\[:([^\]]+)\]

Or you can just use preg_replace_callback and pass an desired replace function to it.

$data = [...];
preg_replace_callback('/\[:([^\]]+)\]/', $str, function (&$matches) use ($data) {
    return doSomethingWithMatches..
});
Philipp
  • 15,377
  • 4
  • 35
  • 52