如何制作一个bbcode来将url标签解析为链接?

Cya*_*ime 1 html css php bbcode

我该如何解析php中的url?我想做到这一点

[url=http://www.google.com]Google[/url]
Run Code Online (Sandbox Code Playgroud)

变成:

<a href="http://www.google.com">Google</a>
Run Code Online (Sandbox Code Playgroud)

这是我用于其他bb代码的代码:

function postparser($post){ 
        $post = str_replace("\n",'END_OF_LINE',$post);

        $post = str_replace("[line]",'HORIZONTAL_LINE',$post);

        $post = str_replace("[bold]",'BOLD_TEXT_START',$post);
        $post = str_replace("[/bold]",'BOLD_TEXT_END',$post);

        $post = str_replace("[yt]",'YOUTUBE_START',$post);
        $post = str_replace("[/yt]",'YOUTUBE_END',$post);

        $post = sanitize($post);

        $post = str_replace("END_OF_LINE",'<br />',$post);

        $post = str_replace("HORIZONTAL_LINE",'<hr />',$post);

        $post = str_replace("BOLD_TEXT_START",'<b>',$post);
        $post = str_replace("BOLD_TEXT_END",'</b>',$post);

        $post = str_replace("YOUTUBE_START",'<iframe width="560" height="315" src="http://www.youtube.com/embed/',$post);
        $post = str_replace("YOUTUBE_END",'" frameborder="0" allowfullscreen></iframe>',$post);

        return $post;
    }
Run Code Online (Sandbox Code Playgroud)

我该怎么做呢?

小智 6

$post = preg_replace('/\[url=(.+?)\](.+?)\[\/url\]/', '<a href="\1">\2</a>', $post);
Run Code Online (Sandbox Code Playgroud)

这将转向:[url = http://google.com] Google [/ url]

进入解析的bbcode文本: 谷歌

您可能希望使用更具体的正则表达式而不仅仅是.+来过滤掉潜在的坏/危险输入.