I need to grab the words out of this string and replace with AND LIKE/NOT LIKE in a sql statement, but I’m pulling my hair out trying to figure it out 🙂
$string = "hello -world !someword ! again |foo &foo AND foo ORfoo";
if (preg_match_all("/AND|OR|\||&|!|\-(\w+)/", "$string", $matches)) {
foreach ($matches as $match) {
foreach ($match as $m) {
// 1. figure out what the delimiter was (!, |, &, -, AND, OR
// 2. create a sql statement from it using the word following the delimiter
// Example:
if ($m = "!") {
$where .= " AND msg NOT like '%".$m."%'";
}
if ($m = "AND") {
$where .= " AND msg like '%".$m."%'";
}
if ($m = "OR") {
$where .= " OR msg like '%".$m."%'";
}
}
}
}
echo $where;
Use the code below to gather your regex matches. Remember, preg_match_all is meant to collect all occurrences of a given pattern. Notice I used preg_match instead. The “\s*” allows you to match whitespace if it exists.
You can then iterate over the $results array to create your MySQL query. The resulting array will look like this.
I added an additional capture to the regex. Your different patterns will be in element 1 and the word will be in element 2.
You can use the code below to create your query fragment: