Saturday, 8 June 2013

PHP - preg_match/preg_replace problems

PHP - preg_match/preg_replace problems

I'm a little confused with preg_match and preg_replace. I have a very long content string (from a blog), and I want to find, separate and replace all [caption] tags. Possible tags can be:
[caption]test[/caption]
[caption align="center" caption="test" width="123"]<img src="...">[/caption]
[caption caption="test" align="center" width="123"]<img src="...">[/caption]
etc.
Here's the code I have (but I'm finding that's it not working the way I want it to...):
public function parse_captions($content) {
    if(preg_match("/\[caption(.*) align=\"(.*)\" width=\"(.*)\" caption=\"(.*)\"\](.*)\[\/caption\]/", $content, $c)) {
        $caption = $c[4];        
        $code = "<div>Test<p class='caption-text'>" . $caption . "</p></div>";
        // Here, I'd like to ONLY replace what was found above (since there can be
        // multiple instances
        $content = preg_replace("/\[caption(.*) width=\"(.*)\" caption=\"(.*)\"\](.*)\[\/caption\]/", $code, $content);
    }
    return $content;
}

No comments:

Post a Comment