Journal(2005) | Blog(2006) | RandomLink | WhoAmI | LiveBookmark | HomePage

<<Previous: Share the URLs (February 2006)  >>Next: Catalyst 的用户鉴定登陆

在文本中寻找 URI 地址

Category: Modules   Keywords: uri find

我们经常碰到这样的任务,在一段文本中找到 URL/URI 地址,然后让这个地址变为可以点击。
最寻常的方法就是用正则表达式来做。不过有时候这不是很理想。

CPAN 中有一个 URI::Find 模块专门来做这事。实例代码如下:

#!/usr/bin/perl
use strict;
use warnings;

use URI::Find;

my $text = <<HTML;
hi, it's from http://www.fayland.org/ then 1313s.com?
HTML

my $finder = URI::Find->new(
   sub {
       my($uri, $orig_uri) = @_;
       return qq|<a href="$uri">$orig_uri</a>|;
   });
$finder->find(\$text);

print $text;

这样 $text 的输出会变为:
hi, it's from <a href="http://www.fayland.org/">http://www.fayland.org/</a> then
1313s.com?
如果想让 1313s.com 也变为可点击,则可以使用 URI::Find::Schemeless

#!/usr/bin/perl
use strict;
use warnings;

use URI::Find::Schemeless;

my $text = <<HTML;
hi, it's from http://www.fayland.org/ then 1313s.com?
HTML

my $finder = URI::Find::Schemeless->new(
   sub {
       my($uri, $orig_uri) = @_;
       return qq|<a href="$uri">$orig_uri</a>|;
   });
$finder->find(\$text);

print $text;

Schemeless 的意思就是没有协议头(如 http )也匹配。
$text 变为:
hi, it's from <a href="http://www.fayland.org/">http://www.fayland.org/</a> the
<a href="http://1313s.com/">1313s.com</a>?
大致如是。详细的查阅 URI::Find , have fun!

<<Previous: Share the URLs (February 2006)  >>Next: Catalyst 的用户鉴定登陆

Options: +Del.icio.us

Related items Created on 2006-02-20 16:41:30, Last modified on 2006-02-20 16:43:26
Copyright 2004-2006 All Rights Reserved. Powered by Eplanet && Catalyst 5.65.