duansengcha9114 2010-11-13 19:09
浏览 33

preg_replace和多个域的数组

i have an array like this:

$array =  array('domain1.com','domain2.net','domain3.org');

any way to replace only these domains into links with preg_replace?

currently have this little function, but parses all the domains:

                function insert_referer($text){
                    $text = preg_replace('#(script|about|applet|activex|chrome):#is', "\\1:", $text);
                    $ret = ' ' . $text;
                    $ret = preg_replace("#(^|[
 ])([\w]+?://[\w\#$%&~/.\-;:=,?@\[\]+]*)#is", "\\1<a href=\"\\2\" target=\"_blank\">\\2</a>", $ret);
                    $ret = preg_replace("#(^|[
 ])((www|ftp)\.[\w\#$%&~/.\-;:=,?@\[\]+]*)#is", "\\1<a href=\"http://\\2\" target=\"_blank\">\\2</a>", $ret);
                    $ret = substr($ret, 1);
                    return $ret;
                }         
  • 写回答

1条回答 默认 最新

  • du1108 2011-01-20 14:35
    关注

    This code does what you wanted:

    $array = array('domain1.com','domain2.net','domain3.org');
    $text = 'Some text including domain1.com/something and http://domain3.org';
    echo preg_replace('/((?:https?:\/\/)?(?:' . implode('|', $array) . ')[-a-zA-Z0-9\._~:\/?#\[\]@\!\$&\'\(\)\*\+,;=]*)/', '\1', $text);
    // Outputs:
    // "Some text including <a href="domain1.com/something">domain1.com/something</a> and <a href="http://domain3.org">http://domain3.org</a>"
    

    I didn't test the code itself so it may (I don't think it would but it's possible) contain typos, but I tested the regexp itself and it works perfectly.

    评论

报告相同问题?

悬赏问题

  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?
  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计
  • ¥15 路易威登官网 里边的参数逆向
  • ¥15 Arduino无法同时连接多个hx711模块,如何解决?
  • ¥50 需求一个up主付费课程