Forum Moderators: coopster & phranque

Message Too Old, No Replies

Replace string with link

using Perl

         

irubin

5:16 am on Mar 21, 2003 (gmt 0)

10+ Year Member



Hello,

I have a certain string, say "foo bar widget" and would like to replace the substring "widget" with a link, so that:

foo bar widget

<becomes>

foo bar <a href="search.cgi?q=widget">widget</a>

Also - this needs to be case insensitive. Any ideas on how to get this done?

Thanks.

Roy

DrDoc

5:31 am on Mar 21, 2003 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Is it always the same word?

If so, you can do this:

$string =~ s/widget/<a href="search.cgi?q=widget">widget<\/a>/ig;

gethan

5:33 am on Mar 21, 2003 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



try:

$text =~ s/widget/<a href='search.cgi?q=widget'>widget<\/a>/gi;

g = do it globally ... not just once
i = case insensitive.

From experience I would recommend using some kind of code around widget - there maybe times when you would want widget to appear in the text...

eg. (using # as the delimiter so you don't have to escape slashes).

$text =~ s#\[url\]widget\[/url\]#<a href='search.cgi?q=widget'>widget</a>#gi;

and better still:

$text =~ s#\[url\](.*?)\[/url\]#<a href='search.cgi?q=$1'>$1</a>#gi;

which would allow you to do this replace on

foo bar [url]widget/[/url/] bar non link widget foo [url]wodgits/[/url/]

Note: url is the code used by brett... had to put in lots of nasty slashes - I think you see what I mean...

HTH

irubin

5:37 am on Mar 21, 2003 (gmt 0)

10+ Year Member



Forget to mention -

I have an array populated with all the keywords that need to replaced. This will done at runtime (when the page is queried). Should I loop for each keyword, or can I build one regex that will do that trick?

Thanks.

nosanity

7:28 am on Mar 21, 2003 (gmt 0)

10+ Year Member



One point to ask, is what language?

[added]
Next time I will read the subject of the post better... ignore me.

:)

noSanity

andreasfriedrich

12:37 pm on Mar 21, 2003 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member




>>I have an array populated with all the keywords that need
>>to replaced


my $rules = join [perldoc.com] '', map [perldoc.com] {
join [perldoc.com]('', '$x =~ s!', $_, '!<a href="search.cgi?q=', $_, '">', $_', '</a>!gi')
} @words;
my $m = eval [perldoc.com] "sub [perldoc.com] {my \$x = shift [perldoc.com]; $rules; return [perldoc.com] \$x;}";
$string = &$m;

BTW how do you make sure that a term will be replaced only when it is ordinary text? If you had string like <p class="term">Some text about something</p> and applied the above code to replace term with a link you would end up with invalid code.

The HTML replace script [webmasterworld.com] I posted in Bag-O-Tricks for Perl - Letīs collect some nice and useful perl scripts [webmasterworld.com] will take care of that.

Andreas