Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight
 
PerlMonks  

Re^2: Highlight a substring

by the_0ne (Pilgrim)
on Apr 06, 2005 at 17:02 UTC ( #445370=note: print w/ replies, xml ) Need Help??


in reply to Re: Highlight a substring
in thread Highlight a substring

I have more of a question than a comment. The first thing I would have thought to do was this...

my $string1 = 'realy long string of html and here is the word long aga +in'; my $string2 = 'long'; + $string1 =~ s/($string2)/<b>$1<\/b>/g; + print "string1: $string1\n";

I know tmtowtdi, but is there another reason that the 2 responses to MonkPaul's question didn't involve s///g?

Thanks again oh wise monks.


Comment on Re^2: Highlight a substring
Download Code
Re^3: Highlight a substring
by ikegami (Pope) on Apr 06, 2005 at 18:09 UTC
    index is much faster than m// when matching a constant string. I'm guessing index + substr is similarly faster than s///. Feel free to benchmark the two.

    By the way,
    $string1 =~ s/($string2)/<b>$1<\/b>/g;
    should be replaced with
    $string1 =~ s/(\Q$string2\E)/<b>$1<\/b>/g;
    in case $string2 contains special characters. Better yet,
    $string1 =~ s/((?:\Q$string2\E)+)/<b>$1<\/b>/g;
    should be a little bit faster.

    I'd also Benchmark the following which has fewer concatenations:

    $string1 =~ s#(?=(?:\Q$string2\E)+)#<b>#g; $string1 =~ s#(?<=(?:\Q$string2\E)+)#</b>#g;

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://445370]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others avoiding work at the Monastery: (9)
As of 2014-09-16 15:50 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    How do you remember the number of days in each month?











    Results (33 votes), past polls