Page 1 of 1

BBCode in PHP

Posted: Tue Aug 05, 2008 4:59 am
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?

Re: BBCode in PHP

Posted: Tue Aug 05, 2008 6:12 am
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;
    }

Re: BBCode in PHP

Posted: Tue Aug 05, 2008 6:57 am
by lostprophetpunk
I am not really how your script works there. I got a bit confused.