1

I feel like an amateur for asking this, but I've been struggling at this for a long time and can't solve the problem.

I'm making a forum with embedded YouTube videos and a rich text editor. I need a function to convert the HTML tag to BBCode, another to convert the BBCode back to HTML.

BBCode to HTML

$message = (get message from database);
$A = '/\[youtube](.*?)\[\/youtube\]/is';
$B = '<object type="application/x-shockwave-flash" data="http://www.youtube.com/v/$1" width="425" height="350"><param name="movie" value="http://www.youtube.com/v/$1"><param name="wmode" value="transparent"></object>';
preg_replace($A, $B, $message);

I need a script that reverses this process, turning the HTML into BBCode. If someone could help me out I would be extremely grateful, or maybe suggest a easier method if one exists, or even a link that could provide some insight into the issue.

Thank you.

2
  • Basically, yeah! Sorry for complicating it :P Commented Mar 14, 2013 at 0:15
  • Don't use regular expressions to parse HTML. You cannot reliably parse HTML with regular expressions. As soon as the HTML changes from your expectations, your code will be broken. See htmlparsing.com/php.html for examples of how to properly parse HTML with PHP modules. Commented Mar 14, 2013 at 3:23

1 Answer 1

1

Try this

$message = 'Some text
<object type="application/x-shockwave-flash" data="http://www.youtube.com/v/abcdefgh" width="425" height="350"><param name="movie" value="http://www.youtube.com/v/abcdefgh"><param name="wmode" value="transparent"></object>
More text
<object type="application/x-shockwave-flash" data="http://www.youtube.com/v/abcdefgh" width="425" height="350"><param name="movie" value="http://www.youtube.com/v/abcdefgh"><param name="wmode" value="transparent"></object>
Even more text';

echo preg_replace("/\<object.*?youtube\.com\/v\/(.*?)\".*?object\>/ims", "[youtube]$1[/youtube]", $message);
Sign up to request clarification or add additional context in comments.

4 Comments

Oh cool, it works. But may I ask how it works? The object tag will be among the user's message. Could it interfere with any of their other content or does it only apply to the object tags in their message?
Yes it will remove other content. If that code is part of a bigger text string it needs tweaking.
That's fine! I can tweak around with it. Thanks a lot for that! :)
Oh you asked how it works. Parenthesis collects the value. I've told the pattern to select everything from <object to /object> but, by identifying the characters before and after the youtube id, only collect the youtube id then replace that selection with just that collected string, and your [youtube] wrapper.

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.