search result case problem

B

Ben Duffy

What perl functions should I use to be able to find a substring in a string,
& replace it with bold text, similar to Google search results highlighting?

for example
search "120gb Hard Disk Drive" for "disk" to result in "120gb Hard
<strong>Disk</strong> Drive"

The way I am currently doing this is...
$prodname = "120gb Hard Disk Drive" ;
$where_desc = "disk";
$prodname =~ s/$where_desc/<strong>$where_desc<\/strong>/gi;

which gives... "120gb Hard <strong>disk</strong> Drive"

The problem is that I want to retain the $prodname's original case.


I have tried using split, to get the string parts before & after the search
word, but can't assign the actual found word to a variable...

($before,$after)= split(/$where_desc/i,$proddesc);
only two variables are returned,
$before = "120gb Hard";
$after = "Drive";

but I can't assign "Disk" to a variable. If I could, then I could rejoin
after formatting.

Any help would be appeciated.
 
A

Anno Siegel

Ben Duffy said:
What perl functions should I use to be able to find a substring in a string,
& replace it with bold text, similar to Google search results highlighting?

for example
search "120gb Hard Disk Drive" for "disk" to result in "120gb Hard
<strong>Disk</strong> Drive"

The way I am currently doing this is...
$prodname = "120gb Hard Disk Drive" ;
$where_desc = "disk";
$prodname =~ s/$where_desc/<strong>$where_desc<\/strong>/gi;

which gives... "120gb Hard <strong>disk</strong> Drive"

The problem is that I want to retain the $prodname's original case.

Capture the match and use the original:

$prodname =~ s{($where_desc)}{<strong>$1</strong>}gi;

Anno
 
J

Jasper

Ben Duffy said:
What perl functions should I use to be able to find a substring in a string,
& replace it with bold text, similar to Google search results highlighting?

for example
search "120gb Hard Disk Drive" for "disk" to result in "120gb Hard
<strong>Disk</strong> Drive"

The way I am currently doing this is...
$prodname = "120gb Hard Disk Drive" ;
$where_desc = "disk";
$prodname =~ s/$where_desc/<strong>$where_desc<\/strong>/gi;

which gives... "120gb Hard <strong>disk</strong> Drive"

The problem is that I want to retain the $prodname's original case.

Why not try:

$prodname =~ s/($where_desc)/<strong>$1<\/strong>/gi;

That seems to work for me. The brackets capture what you actually
match, not just what you're searching for, if you see what I mean.

Jasper
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,142
Messages
2,570,818
Members
47,362
Latest member
eitamoro

Latest Threads

Top