0

I've written a regular expression to strip out BBCode tags - it just strips the allowed tags out (for later counting the string length without the tags).

I'm not an expert when it comes to regular expressions - so after an hour I found this pretty much working:

$pattern = "/\[\/?(i|b|u|url(.*?)|list|li)[\]\[]*\]/i";
$stripped = preg_replace($pattern, '', $text);

It only strips the allowed six tags (and no more - which it is supposed to) and the special tag 'url' which can be extended like 'url=http://someurl'.

I.e.

in:  [url=someurl]Lorem[/url] ipsum [test]dolor[/test] sit [b]amet[/b].
out: Lorem ipsum [test]dolor[/test] sit amet.

But the problem is, that it doesn't just strip out 'url=[sometext]' but also 'urlipsum'. I tried to add an '=' for parsing but couldn't get to the point.

Does anyone has a hint for me how to only strip out url when it comes with the =?

2
  • 1
    BBCode is a language which is too complex to be parsabale by regex. Have you tried a BBCode parser? Commented Jan 10, 2010 at 12:07
  • I have a component for the output but none that just strips all tags. I just use it for counting the length - because the bbcode tags don't count as used characters when inserting tags. The Pear class I found for BBcode couldn't live up to my expectations and did more than I wanted. Commented Jan 10, 2010 at 12:13

3 Answers 3

1

Try:

$pattern = '/\[\/?(i|b|u|url(=[^\]]+)?|list|li)[\]\[]*\]/i';
Sign up to request clarification or add additional context in comments.

1 Comment

This is great! Thank you very much! I added protocols for extra tests - since I don't want other than http(s), ftp and mailto: "/[\/?(i|b|u|url(=(http|https|ftp|mailto)[^]]+)?|list|li)[][]*]/i"
0
  $pattern = "/\[\/?(i|b|u|url=(.*?)|url(?=\])|list|li)[\]\[]*\]/i";

1 Comment

This also strips the url-tag when written without an equal sign - I'll keep it in mind.
0

You may want to change the "greediness" of the quantifiers, try adding "U" pattern modifier or remove the question mark in ".*?", see PHP doc.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.