jkushner jkushner - 1 year ago 76
Perl Question

Simple perl regex replacement

Here is my perl code:

my $var="[url=/jobs/]click here[/url]";
$var =~ /\[url=(.+?)\](.+?)\[\/url\]/<a href="\1" style="text-decoration:none;color:#336699">\2</a>/g

I'm very new to perl so i am aware that its incorrect but how do i perform this
regex replacement

The end result would be a transformation of
<a href="/jobs">click here</a>

sln sln
Answer Source

So, with all the answers you know the substitute form is s///

However, with something this big you should break it up into parts
to make it easier to maintain. And also helps to get out of the
quagmire of delimiter hell.

This uses a pre-compiled regex and a callback function invoked with s///e

use strict;
use warnings;

# Pre-compiled regex
my $rx = qr{\[url=(.+?)\](.+?)\[/url\]};

# Callback
sub MakeAnchor {
   my ($href,$text) = @_;
   return '<a href="' . $href . '" style="text-decoration:none;color:#336699">' . $text . '</a>';

my $input = '[url=/jobs/]click here[/url]';
$input =~ s/$rx/MakeAnchor($1,$2)/eg;

print $input;


<a href="/jobs/" style="text-decoration:none;color:#336699">click here</a>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download