将字符串生成超链接

我正在尝试创建一个函数,它将解析一个字符串并将任何发现的URL替换为该URL的HTML版本。

例如,test.com将变成<a href="http://www.test.com>http://www.test.com</a>

这是我正在使用的代码:

function parse_url (x)
    local domains = [[.ac.ad.ae.aero.af.ag.ai.al.am.an.ao.aq.ar.arpa.as.asia.at.au
       .aw.ax.az.ba.bb.bd.be.bf.bg.bh.bi.biz.bj.bm.bn.bo.br.bs.bt.bv.bw.by.bz.ca
       .cat.cc.cd.cf.cg.ch.ci.ck.cl.cm.cn.co.com.coop.cr.cs.cu.cv.cx.cy.cz.dd.de
       .dj.dk.dm.do.dz.ec.edu.ee.eg.eh.er.es.et.eu.fi.firm.fj.fk.fm.fo.fr.fx.ga
       .gb.gd.ge.gf.gh.gi.gl.gm.gn.gov.gp.gq.gr.gs.gt.gu.gw.gy.hk.hm.hn.hr.ht.hu
       .id.ie.il.im.in.info.int.io.iq.ir.is.it.je.jm.jo.jobs.jp.ke.kg.kh.ki.km.kn
       .kp.kr.kw.ky.kz.la.lb.lc.li.lk.lr.ls.lt.lu.lv.ly.ma.mc.md.me.mg.mh.mil.mk
       .ml.mm.mn.mo.mobi.mp.mq.mr.ms.mt.mu.museum.mv.mw.mx.my.mz.na.name.nato.nc
       .ne.net.nf.ng.ni.nl.no.nom.np.nr.nt.nu.nz.om.org.pa.pe.pf.pg.ph.pk.pl.pm
       .pn.post.pr.pro.ps.pt.pw.py.qa.re.ro.ru.rw.sa.sb.sc.sd.se.sg.sh.si.sj.sk
       .sl.sm.sn.so.sr.ss.st.store.su.sv.sy.sz.tc.td.tel.tf.tg.th.tj.tk.tl.tm.tn
       .to.tp.tr.travel.tt.tv.tw.tz.ua.ug.uk.um.us.uy.va.vc.ve.vg.vi.vn.vu.web.wf
       .ws.xxx.ye.yt.yu.za.zm.zr.zw]]
    local tlds = {}
    for tld in domains:gmatch'%w+' do
       tlds[tld] = true
    end
    local protocols = {[''] = 0, ['http://'] = 0, ['https://'] = 0, ['ftp://'] = 0}

    for pos, url, prot, subd, tld, colon, port, slash, path in x:gmatch
       '()(([%w_.~!*:@&+$/?%%#-]-)(%w[-.%w]*%.)(%w+)(:?)(%d*)(/?)([%w_.~!*:@&+$/?%%#=-]*))'
    do
       if protocols[prot:lower()] == (1 - #slash) * #path
          and (colon == '' or port ~= '' and port + 0 < 65536)
          and (tlds[tld:lower()] or tld:find'^%d+$' and subd:find'^%d+%.%d+%.%d+%.$'
          and math.max(tld, subd:match'^(%d+)%.(%d+)%.(%d+)%.$') < 256)
          and not subd:find'%W%W'
       then
          return string.gsub(x, url, "<a href=\"" .. url .. "\">" .. url .. "</a>")
       end
    end
end

我遇到了一些问题,希望解决:

1)如果字符串x不包含任何URL,则返回nil结果。我希望它保持字符串不变

2)它无法识别内部链接(http://test

3)它无法识别多个子域(http://mysite.whatever.com可行,http://mysite.whatever.co.uk不可行)

4)它将识别同一个URL的重复实例,但不会找到后续的URL。例如,对于字符串http://www.test.com http://www.test.com http://www.whatever.comhttp://www.test.com将被修改两次,但http://www.whatever.com根本不会被识别。

我该如何更改以使其正常工作?

点赞
用户282536
用户282536

这是我最初为此编写的 sane_uri lpeg 模式的用例: https://github.com/daurnimator/lpeg_patterns#uri

示例: (填写你自己的 html_escape 函数)

local lpeg = require "lpeg"
local alpha = lpeg.R("az", "AZ")
local sane_uri = require "lpeg_patterns.uri".sane_uri
local patt = lpeg.Cs((lpeg.Cg(lpeg.C(sane_uri))/function(u, t)
    if t.scheme == "http" or t.scheme == "https" then -- 你的方案白名单
        return "<a href=\""..html_escape(u).."\">"..html_escape(u).."</a>"
    end
end+(alpha^0*(1-alpha)))^0);
print(s:match("some http://example.com/ text"))

上面的示例使用在 lpeg 手册 中描述的 "全局替换" 方法,以及类似于 "仅在单词边界查找模式" 示例的代码。

2015-09-15 00:55:30