Home  |  Linux  | Mysql  | PHP  | XML
From:Chris Sarnowski Date:Sat Oct  7 15:29:35 2006
Subject:Re: Let perl replase words
On Oct 7, 2006, at 2:59 PM, Eelco Alosery wrote:

>
> Hello,
>
> I have a small, (maby big) problem.
>
> Im writing a search script for my site, and wand to do some  
> replacing of words.
>
> I have a string that contains for example this :
> Test this is a smal test script line.
>
> Now i have a search patern :
> test
>
> What i want to do is this.
> Test and test must be replased by <b>Test</b> and <b>test</b>
>
> Thus al (case insensative) matches to test must be converted to  
> bold words.
>
> I have tested a lot, and the best result sovar is this code :
> $head =~ s/$replace/<u>$replace<\/u>/gi;
>
> But this code replases Test to <b>test</b> it is realy convertet to  
> the original search patern.
>
> Any help whit this is very welcome.
>
> Thanks,
> Eelco Alosery


$head =~ s/($replace)/<u>$1<\/u>/gi;

This will match the value of $replace regardless of case. But $1 will  
preserve the case of the matched string, so will do what you want.

Just for fun, here is a program with a function that will replace any  
string with a different string and will match the case of each  
character of the original string in the corresponding position of the  
replacement string.

---- begin testcase.pl ----
#!/usr/bin/perl -w

use strict;
sub preserve_case($$) {
   my ($from, $to) = @_;
   my ($lf, $lt) = map length, @_;
   if ($lt < $lf) {
      $from = substr $from, 0, $lt;
   } else {
      $from .= substr $to, $lf;
   }
   return uc $to | ($from ^ uc $from);
}

### begin main

my $string = shift;
my $orig = shift;
my $replace = shift;
$string =~ s/($orig)/preserve_case($1, $replace)/egi;
print $string, "\n";

---- end testcase.pl ----

% testcase.pl "here is a foo string with a proper Foo and a FoO" foo bar
here is a bar string with a proper Bar and a BaR

Navigate in group perl.macperl.anyperl at sever nntp.perl.org
Previous Next




  
© No Copyright
You are free to use Anything
Site Maintained by PHP Developer
Powered By PHP Consultants