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?
$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?
ASKER
Suggest you construct the RLIKE expression in a separate PHP variable, like this:
http://iconoun.com/demo/temp_steva.php?q=word
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);
}
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}[[:>:]]'
";
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
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
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.