Darren Ferguson - Weblog

Perl - Replacing words within a string

A brief demo of using regular expressions to replace words within a string using Perl.

Marco Tag

<?PERL_MACRO id="strike" value="If i use the words Umbraco and
Perl in this sentence they should be struck out. Even if I say perl and Umbraco
more than once. Umbraco."/>"</?PERL_MACRO>

Marco Output

PERL FOR UMBRACO: The remote server returned an error: (405) Method Not Allowed. requesting http://www.darren-ferguson.com:80/plex/strike.plex

Perl Source

use strict;
use utf8;
use CGI;
use Date::Format;

my $query = new CGI;
print $query->header(-charset => 'utf-8');
my $val = $query->param('value');
if($val) {
	my @words = ('umbraco', 'perl');
	foreach my $word (@words) {
		$val =~ s|($word)|<strike>$1</strike>|igsm;	
	}
	
	$val =~ s/((^\w)|(\s\w))/\U$1/xg; # Uppercase first character of each word
	print $val;	
} else {
	print 'no value specified';
}