Link to home
Start Free TrialLog in
Avatar of steva
steva

asked on

Using a PHP variable in an RLIKE regex

I'd like to search the Categories table for the $term passed in. The code below doesn't work.

$term= ($_POST['term']);

"SELECT *
FROM Categories
WHERE Cat4 RLIKE  '[[:<:]]$term[[:>:]]'
";

I've also tried "[[:<:]]$term[[:>:]]" but that doesn't work either.

Is there a way to use a variable in the RLIKE regex?
Avatar of Ray Paseur
Ray Paseur
Flag of United States of America image

Here's a link to the man page.
http://dev.mysql.com/doc/refman/5.7/en/regexp.html

Can you just tell us in plain language what you are trying to achieve?  I'm sure there is a correct syntax, but I don't understand the objective from the example posted here.
Avatar of steva
steva

ASKER

Cat4 is one column of a 'Categories" table and I want to return all the records where the Cat4 field contains the word passed in as $term.  I got the '[[:<:]]word[[:>:]]' format from the man page you linked to:

User generated image
I've also tried backslashing the $ but that doesn't work.
Suggest you construct the RLIKE expression in a separate PHP variable, like this:
http://iconoun.com/demo/temp_steva.php?q=word
<?php // demo/temp_steva.php
/**
 * http://www.experts-exchange.com/questions/28932231/Using-a-PHP-variable-in-an-RLIKE-regex.html#a41501765
 */
error_reporting(E_ALL);
echo '<pre>';

// ACQUIRE THE REQUEST VARIABLE
$q = !empty($_GET['q']) ? $_GET['q'] : NULL;
if ($q)
{
    // BUILD THE REGEX (RLIKE) CLAUSE
    $regex = '[[:<:]]' . $q . '[[:>:]]';
    $query = "SELECT 'a word a' REGEXP $regex";

    var_dump($query);
}

Open in new window

Avatar of steva

ASKER

Thanks Ray for putting that together. Someone else, though,  suggested just putting the variable inside of {}, and it worked!

$term= ($_POST['term']);

"SELECT *
FROM Categories
WHERE Cat4 RLIKE  '[[:<:]]{$term}[[:>:]]'
";

Open in new window

They weren't able to explain why it worked. I suspect, though,  that the curly braces drew PHP's attention immediately to the enclosed variable so the variable got expanded before anything else was looked at.
ASKER CERTIFIED SOLUTION
Avatar of Ray Paseur
Ray Paseur
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial