jackpf Posted February 19, 2009 Share Posted February 19, 2009 Hi all, Just wondering, is there a way to use preg_replace() to replace tags which aren't closed in the right order? For example- If someone were to have [colour=red]red[colour=blue]blue[/colour][/colour] I've noticed that preg_replace() can't handle it, and cuts out one of the tags... Thanks for any help, Jack. Quote Link to comment https://forums.phpfreaks.com/topic/145849-multiple-bbcoderegex-tags/ Share on other sites More sharing options...
Goldeneye Posted February 23, 2009 Share Posted February 23, 2009 It's not terribly hard to do; here's what I am currently using. <?php $search = array('/\[b\](.*?)\[\/b\]/si', '/\[i\](.*?)\[\/i\]/si', '/\[u\](.*?)\[\/u\]/si', '/\[align\=(left|center|right)\](.*?)\[\/align\]/si', '/\[img\](.*?)\[\/img\]/si' ); $replace = array('<b>$1</b>', '<i>$1</i>', '<u>$1</u>', '<div style="text-align: $1;">$2</div>', '<a href="$1"><img src="$1" class="image"></a>' ); $str = preg_replace($search, $replace, $str); //$str is the formatted text; you can simply echo it, or do whatever else ?> Though this is fairly basic, you can still do quite a few things with it. It takes a little more work if you want to use quote or code tags. You can also put this inside a function (as I do). This method only matches on correctly matched tags and doesn't leave you with the hassle of unmatched pseudo-tags which may ruin everyother text that comes after it. And yes, they can also be nested. Quote Link to comment https://forums.phpfreaks.com/topic/145849-multiple-bbcoderegex-tags/#findComment-769539 Share on other sites More sharing options...
jackpf Posted February 23, 2009 Author Share Posted February 23, 2009 Yeah, this is something simliar to what I currently have. However, the problem I'm having is that if someone uses multiple tags without closing them in the proper order, it only matches the first tags. For example: [noparse] quote 1 quote 2 [/noparse] This would only display the first occurance of the tag. I'm currently using this as a workaround: for($i = 0; $i <= 5; $i++) { $str = preg_replace($exist, $replace, $str); } But this only works for how ever many recurances I set it to. What I would preferably do is find out how many matches there of a tag, and then repeat preg_replace() that number of times. However, I'm having difficulty using preg_match with arrays... So yeah Lol, sorry for the long-ness. Quote Link to comment https://forums.phpfreaks.com/topic/145849-multiple-bbcoderegex-tags/#findComment-769546 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.