Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Regex - help

Status
Not open for further replies.

perlone

Programmer
May 20, 2001
438
US
Hello,

I have a database filled with keywords and the program let you search for it. For example of my data:

[keywords]
quest,alien,campy,3d

What I want to do is let you search through the keywords. So I have the following:

$q=param('q');

if ($keywords =~/$q/i) { print "match"; }

It does work if I searh for 'quest', but If I type something like: some quest like, it should find the search since 'quest' is one of the keywords. For some reason, it doesn't search for it and gives an error. Anyone know what is wrong with it?:(. Thank You so much for reading.
 
That's because "quest,alien,campy,3d" doesn't match the entire pattern "some quest like" which is what you're searching for (it does match part of it, but parts don't count, it's all or bust). Generally, you search in a string for keywords, not in a list of keywords for a string (since generally strings are long and keywords are limited). This whole process can be done backwards, though, if that's what you're after. I'd probably suggest something like this:
Code:
$keywords =~ /,/|/g;
print "match" if($q =~ /$keywords/i);
Since the elements in $keyword probably exist originally as a list, join them with | instead of a comma (and maybe want to escape the words, too, if they might include non-word characters).

Also of note, searching for each term individually is faster than searching for all of them |-ed together. Check the FAQ's for regex optimizing.

----------------------------------------------------------------------------------
...but I'm just a C man trying to see the light
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top