paranitips

Never stop learning! がモットーのゆるふわエンジニアブログ

テキスト中にあるURLを抽出し、リンク(aタグ)に変換する

テキスト中にあるリンクがある場合は、ちゃんとクリックできるリンクにして出力したい!
ということで、いろいろ調べてみました。

URLを抽出する

textからURLを抽出するだけであれば、URI.extractを使えばOKです。

text = 'aaaaa http://xxx.com bbbbb http://yyy.com'
URI.extract(text,['http','https'])
=> ["http://xxx.com", "http://yyy.com"]

URI.extractを利用するパターン(NGパターン)

URI.extractを利用してgsubでURLをaタグに置換します。

text = 'aaaaa http://xxx.com bbbbb http://yyy.com'
URI.extract(text,['http','https']).uniq.each do |url|
    sub_text = ""
    sub_text << "<a href=" << url << ">" << url << "</a>"
    text.gsub!(url, sub_text)
end
=> "aaaaa <a href="http://xxx.com">http://xxx.com</a> bbbbb <a href="http://yyy.com">http://yyy.com</a>"

ただ、この場合、うまくいかない場合があります。

text = 'aaaaa http://xxx.com/hoge bbbbb http://xxx.com'
URI.extract(text,['http','https']).uniq.each do |url|
    sub_text = ""
    sub_text << "<a href=" << url << ">" << url << "</a>"
    text.gsub!(url, sub_text)
end
=> "aaaaa <a href="<a href="http://xxx.com">http://xxx.com</a>/hoge"><a href="http://xxx.com">http://xxx.com</a>/hoge</a> bbbbb <a href="http://xxx.com">http://xxx.com</a>"

aタグ中のhref=http://xxx.comも置換させてしまい、変なことになっていました。

http://xxx.com/hoge  
=> <a href="http://xxx.com/hoge">http://xxx.com/hoge</a>  
=> <a href="<a href="http://xxx.com">http://xxx.com</a>/hoge"><a href="http://xxx.com">http://xxx.com</a>/hoge</a>

URI.regexpを利用するパターン(OKパターン)

URI.regexpを利用して正規表現を使ってURLを置換します。

text = 'aaaaa http://xxx.com/hoge bbbbb http://xxx.com'
uri_reg = URI.regexp(%w[http https])
text.gsub!(uri_reg) {%Q{<a href="#{$&}">#{$&}</a>}}
=> => "aaaaa <a href="http://xxx.com/hoge">http://xxx.com/hoge</a> bbbbb <a href="http://xxx.com">http://xxx.com</a>"

こちらのほうが簡単&完璧です。

以上です。

参考