This question already has an answer here:
I'm trying to use preg_match_all to find instances of a pattern in text, then use that pattern to instantiate a class and finally call a class function to print replacement text for the matching pattern. I don't know if I'm going about it the right way.
I can find and replace this pattern [bandcamp=http://bandcamp-page.com]1[/bandcamp] with this preg_replace function
$text = preg_replace ("/\[bandcamp=(.+?)\](.+?)\[\/bandcamp\]/", "replacement text here", $text);
But I want to use the matches to create a BandcampAlbum object and call it's player() function which prints out html. This is what I'm trying but to no avail so far.
if (preg_match_all ("/\[bandcamp=(.+?)\](.+?)\[\/bandcamp\]/", $text, $matches)) {
foreach ($matches[0] as $match) {
preg_replace ("/\[bandcamp=(.+?)\](.+?)\[\/bandcamp\]/", "", $text);
$bc = new BandcampAlbum($match[0], $match[1]);
$bc->player();
}
}
The preg_replace in the foreach loop is intended to just get rid of the matching text. The matching seems to work so I'm guessing I'm doing it the wrong way rather than making a regular expression error. Any suggestions welcome.
</div>
As stated in the comments; what you are probably after is preg_replace_callback. Here is an example of its usage with your problem:
function getBandCampMarkup($matches){
$bc = new BandcampAction($matches[1], $matches[2]);
return $bc->player();
}
$data = preg_replace_callback("/\[bandcamp=(.+?)\](.+?)\[\/bandcamp\]/", "getBandCampMarkup", $data);
echo $data;
This is of course assuming the $bc->player()
returns a string of the output. If this function just echos the data then you can can use ob_start
and ob_get_clean
to capture the output as a string as so:
ob_start();
$bc->player();
return ob_get_clean();