如何将图像,HTTP URL和电子邮件与Perl代码字符串分开



这是一个聊天程序。我设法将图像与大多数文本分开,但它将其嵌入到字符串中。不知道 URL 将在字符串中的位置,如果键入是在它之前还是之后,它就会出现在字符串中! 我需要它来分离并仅将图像正则表达式 URL 放入 s/$image//中。

我已经尝试过循环,foreach 循环并用 for 循环崩溃了整个系统! 我确实将图像就位,但前提是我为它留下了一整行空白。网页也是如此。

if (($searchhttp = m/^http/sig) 
&& ($search_image = m/(.jpg|.jpeg|.gif|.png)/ig)) {
@jpgimage = @_;
$jpgimage = $jpgimage[0];
$jpgimage =~ grep(/(^https?://)?([da-z.-]+).([a-z.]{2,6}) ([/w .-]*)*/?(?:.jpg|.jpeg|.gif|png)$/sig);
$image = substr($jpgimage, 0);
($image) = split(/s+/, $jpgimage);
chomp($image);
$filter =~ s/$image/<img src ='$image' align ='left'>/; 
print $image.'<BR>';
#print $jpgimage.'<BR>';
}

如果我只把它放在一行上,它会起作用......如果我在它之前或之后键入它,它不会。 它包括 a href 或 img src 中的整个字符串。

我需要找到一种方法将其从字符串中取出

例。。。

它从该行中取出整个文本并将其放在右括号中,只有一个长字符串...... "测试这是否有效 http://172.31.4.253/images/joe.jpg" "https://www.perltutorial.org 让我们试试这个">

我花了一个月的时间在这上面...带有此代码的输出是我得到的最好的!

可能有并且很可能不止一个图像。

这是我粘贴 5 张图片后的结果,一张前面有 Test 一词,这 4 张放在 img src 中......

http://172.31.4.253/images/joe.jpg
https://www.perltutorial.org/wp-content/uploads/2012/11/Perl-Tutorial.jpg
http://172.31.4.253/images/joe.jpg
https://www.perltutorial.org/wp-content/uploads/2012/11/Perl-Tutorial.jpg

URL解析和处理并非易事。很容易出错,因此如果可能的话,应该把它留给经过实战测试的模块。请考虑此代码。

use URI;
use URL::Search qw(extract_urls);
my $webpage = join "", <DATA>; # wherever your data comes from
for my $url (extract_urls $webpage) 
{
my $url_object    = URI->new( $url );
my $host_ok       = $url_object->host =~ /.(com|net|jp|org|uk)$/i;
my $is_image      = $url_object->path =~ /.(jpg|jpeg|gif|png)$/i;
my $save_url      = $url_object->canonical;
my $regex_for_url = quotemeta( $url );
$webpage =~ s/$regex_for_url/<img src="$save_url">/g
if $host_ok && $is_image;
}
print $webpage;
__DATA__
https://docs.perl6.org
https://github.xxx/foo.gif
https://docs.perl6.org/camelia.png
https://docs.perl6.org/camelia.gif

输出

https://docs.perl6.org
https://github.xxx/foo.gif
<img src="https://docs.perl6.org/camelia.png">
<img src="https://docs.perl6.org/camelia.gif">

最新更新