doucheng3811 2010-06-21 22:11
浏览 124
已采纳

注释代码的正则表达式问题

I am currently making a homepage where logged in users can write comments. The comment string is first run through a function that str_replaces emoticons. After that I want it to exchange

[url=www.whatever.com]linktext[/url]

with:

<a href='www.whatever.com'>linktext</a>

The reason for this is that I want to strip the text for all the html code that isn't controlled by my comment code, in case some users decide to get creative-

and thought it would be best to use preg replace but the code I ended up with (Partially from reading about reg exp from my trusty "O reilly Sql and Php"-book and partially from the web) Is pretty bonkers, and most importantly, doesn't work.

Any help would be appreciated, thanks.

It's probably possible to exchange the entire code, not in 2 segments like I have done. Just decided on that getting 2 smaller parts to work first would be easier, and then merge them afterwards.

code:

function text_format($string)
{
    $pattern="/([url=)+[a-zA-Z0-9]+(])+/";
    $string=preg_replace($pattern, "/(<a href=\')+[a-zA-Z0-9]+(\'>)+/", $string);
    $pattern="/([\/url])+/";
    $string=preg_replace($pattern, "/(<\/a>)+/", $string);    
    return $string;
}
  • 写回答

3条回答 默认 最新

  • douhao2011 2010-06-21 22:20
    关注

    I experimented a bit with the following:

    function text_format($string)
    {
        return preg_replace('#\[url=([^\]]+)\]([^\[]*)\[/url\]#', '<a href="$1">$2</a>', $string);
    }
    

    However, one immediate fault with this is that if linktext is empty, there will be nothing between <a> and </a>. One way around it would be to do another pass with something like this:

    preg_replace('#<a href="([^"]+)"></a>#', '<a href="$1">$1</a>', $string);
    

    Another option would be to use preg_replace_callback and put this logic inside your callback function.

    Finally, this is obviously a common "problem" and has been solved many times by others, and if using a more mature open sourced solution is an option, I'd recommend looking for one.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 基于双目测规则物体尺寸
  • ¥15 wegame打不开英雄联盟
  • ¥15 公司的电脑,win10系统自带远程协助,访问家里个人电脑,提示出现内部错误,各种常规的设置都已经尝试,感觉公司对此功能进行了限制(我们是集团公司)
  • ¥15 救!ENVI5.6深度学习初始化模型报错怎么办?
  • ¥30 eclipse开启服务后,网页无法打开
  • ¥30 雷达辐射源信号参考模型
  • ¥15 html+css+js如何实现这样子的效果?
  • ¥15 STM32单片机自主设计
  • ¥15 如何在node.js中或者java中给wav格式的音频编码成sil格式呢
  • ¥15 不小心不正规的开发公司导致不给我们y码,