Last active
December 13, 2017 15:49
-
-
Save montyanderson/fe110c9b130ca90ab9b430f1aa7b6704 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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