[Solved] Adding a term to each item of a boolean query in PHP (reg exp?)


I made the following observation from the example you posted: All you want to do is replace the tokens like C++ with a token of the form skill=C++, the rest of the query is unchanged. If that is not always true, you might need a more complex solution, but if that’s enough for you, the following should work:

$expr="C++ AND ((UML OR Python) OR (not Perl))";

// remove tokens that will not be replaced, here `(`, `)`, and `not`
$trimmed = str_replace(['(', ')', 'not'], ['', '', ''], $expr);

// split string based on the keywords `AND` and `OR` (case insensitive)
// keywords will also not be replaced
$tokens = preg_split('/AND|OR/i', $trimmed);

// create replacement tokens without leading/trailing whitespace
$replacementTokens = [];
foreach ($tokens as &$token) {
    $token = trim($token);
    $replacementTokens[] = "skill=$token";
}

// replace tokens and construct the query
$where = str_replace($tokens, $replacementTokens, $expr);
$query = "SELECT * FROM candidates WHERE $where";

As said, this solution might not work if you need more complex behaviour. You also might need to extend the keyword lists. But for the simple use case you provided, it avoids the need to actually parse the query.

On a final note, make sure that you sanitise your user inputs, so you’re not susceptible to SQL injections.

2

solved Adding a term to each item of a boolean query in PHP (reg exp?)