Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I'm trying to parse a text field in a content management system to take all instances of a URL (i.e. ABC.com) and make it a link. I've used the following code, but it only works if there is only one instance of a URL. Furthermore, if I have html code in the text field for an image, it messages the image code up. Here's what I have:

$text =~ s!(^\s+\.com)!$1!gi;

I think I need a way to do a loop or something that will enable me to read through the text to find all instances of a URL. I would also need to tell the script to ignore existing image codes. Thanks.

Replies are listed 'Best First'.
Re: Help with turning urls to links
by Andre_br (Pilgrim) on Apr 10, 2005 at 01:37 UTC
    Hello budy,

    It seems your regexp isnīt quite precise for what you are lloking for. Despite that, to loop through all the ocorrences, you have only to include the regexp (a match one, and not a substitute like the one you wrotte) as a condition in a while loop. Just as easy as that! Take a look:

    while ( $text =~ m!(^\s+\.com)!gi; ) { # the "g" tells Perl that this +can work as a loop! print $1; # or whatever you want to do with the captured link. }
    Now itīs a matter of just adjusting your regexp. I would try something like: (inside the condition)

    $text =~ /a href="(.*?)"/gi; # The ? modifier after another modifier t +ells perl not to be greedy in the *, stopping, here, before the first + \" (instead of swallowing all the string as it would with "."
    Hope I did help!

    Cheers

    André

Re: Help with turning urls to links
by merlyn (Sage) on Apr 10, 2005 at 16:41 UTC