Doug
Doug

Reputation: 869

Regex errors in MySQL (same regex works in PHP)

I'm working on a search function to take user input and search a mysql fields The idea is to split up the words a user searches for and look for each term in the field(s) in question.

The code used to build the regex I am using was copied from a working pure PHP script (the regex seems to work fine with PHP, so I suspect it is a difference in regex flavor)

Forgive me if this is an obvious problem, still getting a feel for regex.

First I will show you the queries I run and the errors I get

"SELECT * from `images` WHERE ( `name` REGEXP '^(?=.*gallardo).*$' OR `meta` REGEXP '^(?=.*gallardo).*$' ) ORDER BY `changestamp` DESC

Got error 'repetition-operator operand invalid' from regexp"

SELECT * from `images` WHERE ( `name` REGEXP '^(?=.*gallardo)(?=.*lambo).*$' OR `meta` REGEXP '^(?=.*gallardo)(?=.*lambo).*$' ) ORDER BY `changestamp` DESC

gives the same error

to compile this regex, I take user submitted input like "gallardo lambo" and run this PHP procedure

if(isset($_GET['keyword'])){

        $searchterms = explode(' ',$_GET['keyword']);

        $regstr = '^';

        foreach($searchterms as $i => $v)
        {
            if($v)
                $regstr .= '(?=.*'.preg_replace('/[-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/', "\\$&", $v).')'; 
        }

        $regstr .= '.*$';

    }

then I put it in the query like

"( `name` REGEXP '$regstr' OR `meta` REGEXP '$regstr' )"

When I use this method with php's preg_match(), it seems to work.

Any insight? Feel free to tell me that I have no idea what I'm doing.

Thanks!

Upvotes: 2

Views: 958

Answers (1)

eggyal
eggyal

Reputation: 125865

MySQL regex are more limited than PHP - they don't support back references or lookahead. See the manual.

You may want to look into fulltext search instead.

Upvotes: 5

Related Questions