#!perl -wl # vim: set ts=8: # how to replace certain text (your $name) with a link (to $url) # based on what tags it is in inside the url # the one problem i see is that if text is already in then we # embed an into it, the text after the href but # before the end of the original will lose its properties. # this can be accounted for, but i'm lazy use strict; use HTML::Parser; # global variables our ($name, $url, @tagstack, $out) = qw{pizza http://www.parseerror.com/}; # sub defs sub start { my ($tag, $attr, $text) = @_; $tag .= " href" if defined $attr->{"href"}; push @tagstack, $tag; output($text); } sub end { my ($tag, $text) = @_; shift @tagstack while (@tagstack && $tagstack[0] !~ /^$tag$/); shift @tagstack if @tagstack; output($text); } sub text { my ($text) = @_; if ($text =~ /\b$name\b/ && canreplace() && unlinked()) { $text =~ s#\b$name\b#$name#g; } output($text); } sub output { my ($txt) = @_; $out .= $txt if defined $txt; } # are we inside a tag we don't want to link? sub canreplace { return ! grep {m/^(head|title)$/} @tagstack; } # are we inside a link right now? sub unlinked { return ! grep {m/^a href$/} @tagstack; } # start code my $p = HTML::Parser->new( "start_h" => [ \&start, "tagname, attr, text" ] ,"end_h" => [ \&end, "tagname, text" ] ,"text_h" => [ \&text, "text" ] ); $p->parse(q{