[thelist] Perl Question / Logic

Dean Mah dmah at members.evolt.org
Sun Jan 12 16:15:22 CST 2003


Not sure why you think that a regular expression would be inelegant.
Anyway, you could try something like:

   my %mapping = ('NFL'      => 'http://www.nfl.com/',
                  'football' => 'http://www.football.com/');

   foreach my $keyword (keys %mapping) {
      $string =~ s/$keyword/<a href="$mapping{$keyword}">$keyword</a>/g;
   }

You'll need to be careful that the regex doesn't match partial words
though.  Or something like:

   my $newstring = '';

   while ($string =~ /([^\s\n]+)([\s\n]?)/g) {
      if (defined($mapping{$1})) {
         $newstring .= $mapping{$1};
      }
      else {
         $newstring .= $1;
      }

      $newstring .= $2;
   }

   $string = $newstring;

Or using the 'index' function to tokenize the string and replace the
appropriate tokens.

Lot's of different ways.

Dean


On Sun, Jan 12, 2003 at 11:27:11AM -0800, Kevin wrote:

> I have a list of keywords associated with links and would like to replace
> each keywords with each respective link. For example:
>
> keyword             link
> ======================
> NFL                    http://www.nfl.com/
> football                http://www.football.com/
>
>
> The original string
>
> $string = qq{NFL football is a great sport};
>
> Should become:
>
> $string = qq{<a href="http://www.nfl.com/">NFL</a> <a
> href="http://www.football.com/">football</a> is a great sport};
>
>
> The keyword index will be dyanmic (reside in the db). Is there a nice and
> elegant to this or is =~ s/ for each keyterm the only way to do this?



More information about the thelist mailing list