BBCode in PHP

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
lostprophetpunk
Forum Newbie
Posts: 21
Joined: Sat May 31, 2008 3:49 am

BBCode in PHP

Post by lostprophetpunk »

I am creating a comment system.

I have got the basic BBCode stuff down like bold, italics, underline and coloured.

But the thing I am having trouble with is the 'url' code.

The code for the 'url' tag is below...

Code: Select all

$Text = preg_replace ('/\[url\=(.*?)\](.*?)\[\/url\]/is', '<a href="$1">$2</a>', $Text);
When I tested it, it just seems to place my website address before the typed in address like so...

Code: Select all

http://www.mywebsite/typedinaddress
How could I fix this problem?
User avatar
s.dot
Tranquility In Moderation
Posts: 5001
Joined: Sun Feb 06, 2005 7:18 pm
Location: Indiana

Re: BBCode in PHP

Post by s.dot »

Very loaded question. There's some good examples in the code snippet forum. Here's a working copy of what I have on some of my web sites..

Code: Select all

function replaceURLTags($text){
        if(preg_match("^\[url=(.+?)\](.+?)\[/url\]^im",$text,$urls)){
            $text = preg_replace_callback(
            '^\[url=(.+?)\](.+?)\[/url\]^im',
                create_function(
                    '$urls',
                    'return \'<a href="\'.trim($urls[1]).\'" target="_blank">\'.trim($urls[2]).\'</a>\';'
                ),
            $text);
        }
        if(preg_match("^\[url\](.+?)\[/url\]^im",$text,$urls2)){
            $text = preg_replace_callback(
            '^\[url\](.+?)\[/url\]^im',
                create_function(
                    '$urls2',
                    'return \'<a href="\'.trim($urls2[1]).\'" target="_blank">\'.trim($urls2[1]).\'</a>\';'
                ),
            $text);
        }
    
        return $text;
    }
    
    function reverseURLTags($text){
        if(preg_match_all("#<a href=\"(.+?)\" target=\"_blank\">(.+?)</a>#im",$text,$rurls)){
            $i=0;
            foreach($rurls[0] AS $url){
                $text = str_replace($url,"[url={$rurls[1][$i]}]{$rurls[2][$i]}[/url]",$text);
                $i++;
            }
        }
        return $text;
    }
Set Search Time - A google chrome extension. When you search only results from the past year (or set time period) are displayed. Helps tremendously when using new technologies to avoid outdated results.
lostprophetpunk
Forum Newbie
Posts: 21
Joined: Sat May 31, 2008 3:49 am

Re: BBCode in PHP

Post by lostprophetpunk »

I am not really how your script works there. I got a bit confused.
Post Reply