Jump to content

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.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.