Jump to content

Multiple bbcode/regex tags.


jackpf

Recommended Posts

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.

Link to comment
https://forums.phpfreaks.com/topic/145849-multiple-bbcoderegex-tags/
Share on other sites

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.

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.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.