I have a string which looks like:
$data = '
Some string
[code=cpp]
int a = 5;
[/code]
Another string
[code=php]
echo "5";
[/code]';
And a function which takes 2 arguments: data inside code-tag and language (cpp, php, …):
function Foo($data, $lang) { echo ...RESULT...; }
What is the best way to replace all code-tags inside $data using my Foo function? The result should be:
$data =
'Some string' .
Foo('int a = 5;', 'cpp') .
'Another string' .
Foo('echo "5";', 'php');
function Foo($matches)
{
echo SOME_ANOTHER($matches[2], $matches[1]);
}
preg_replace_callback('#\[code=(.*?)\](.*?)\[/code\]#si' , 'Foo', $data);
But this code doesn’t save text outside the code-tags.
1 Answer