Skip to content

Instantly share code, notes, and snippets.

@montyanderson
Last active December 13, 2017 15:49
Show Gist options
  • Save montyanderson/fe110c9b130ca90ab9b430f1aa7b6704 to your computer and use it in GitHub Desktop.
Save montyanderson/fe110c9b130ca90ab9b430f1aa7b6704 to your computer and use it in GitHub Desktop.
<?php
function searchQuery($query, $fields, $wrap = true) {
$keywords = explode(" ", $query);
foreach($keywords as $key => $keyword) {
$keywords[$key] = preg_replace("/[^[:alnum:][:space:]]/u", '', $keyword);
}
/* build search query */
$statements1 = array();
foreach($keywords as $keyword) {
$statements2 = array();
foreach($fields as $field) {
array_push($statements2, "`$field` LIKE '%$keyword%'");
}
array_push($statements1, "(" . implode(" OR ", $statements2) . ")");
}
if($wrap == true) {
return "(" . implode(" AND ", $statements1) . ")";
} else {
return implode(" OR ", $statements1);
}
}
echo searchQuery("pink moon", array(
"artist",
"album"
));
// ((`artist` LIKE '%pink%' OR `album` LIKE '%pink%') AND (`artist` LIKE '%moon%' OR `album` LIKE '%moon%'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment