[San-Diego-pm] Text substitution

Menolly menolly at mib.org
Mon May 1 14:44:24 PDT 2006


On Mon, 1 May 2006, Joel Fentin wrote:

> The following code adds bold tags to the desired text. But it also
> changes the case.
>
> $Text = 'Aaa bbb AAA bbb aaa';                #original text
> $SearchFor = 'aAa';                           #what we're looking for
> $Text =~ s/$SearchFor/<b>$SearchFor<\/b>/gi;  #disp search text bold

Use a backreference:
$Text =~ s/($SearchFor)/<b>\1<\/b>/gi;

> There might be a nifty regular expression that adds the tags but
> inflicts no change of case. I haven't figured it out.
> =================================
> I solved the problem with this unhandy code:
>
> $Where = length($Text);                  #start search at end of string
> $CopyOfText = lc($Text);                      #make a low case copy
> $CopyOfSearchFor = lc($SearchFor);            #make a low case copy
> $SearchForLength = length($SearchFor);
> while($Where > -1)                    #loop while desired text is found
> {
>   $Where = rindex($CopyOfText,$CopyOfSearchFor,$Where); #locate desired
> text in string
>   if($Where > -1)                      #if desired text is in string...
>   {
>     $ExistingText = substr($Text, $Where, $SearchForLength); #get a
> copy of it
>     substr($Text, $Where, $SearchForLength) = "<b>$ExistingText</b>";
> #add bold tags to it
>     $Where--;                          #next search starts 1 chr to left
>   }
> }
>
>

-- 
menolly at mib.org                    http://www.livejournal.com/~nolly/

On that day, many will say to me, "Lord, Lord, did we not prophesy in
your name, and cast out demons in your name, and do many mighty works
in your name?" And then will I declare to them, "I never knew you;
depart from me you evildoers." -- Matt 7:20-23, RSV


More information about the San-Diego-pm mailing list