CodeIgniter中分割带双分隔符的标签字符串并实现精准LIKE查询
Fixing Pipe-Wrapped Tag Queries in CodeIgniter
The issue with your current code stems from two key problems:
- Exploding the string
|login||background||signup||material-design|using|creates empty string elements (from consecutive pipes and leading/trailing pipes). These empty values make youror_likeclauses match every row (sinceLIKE "%%"returns all records). - You aren’t wrapping tags in pipes within your
LIKEcondition, which defeats the purpose of avoiding partial matches (like catching "MySQL" when searching for "sql").
Here’s the corrected approach:
Step 1: Clean the Tag Array
First, filter out empty values from the exploded array to eliminate useless elements:
$snippettag_id = explode('|', $snippet_tags); // Remove empty strings from the array $clean_tags = array_filter($snippettag_id);
Step 2: Build Exact Tag Match Conditions
For each valid tag, wrap it in pipes in your or_like call. This ensures you only match tags fully enclosed in pipes, preventing unintended partial matches:
foreach($clean_tags as $tag) { // Wrap the tag with pipes for precise tag matching $this->db->or_like('snippets_name', "|{$tag}|"); }
Full Corrected Code
Putting it all together with a safety check for empty tag arrays:
$snippettag_id = explode('|', $snippet_tags); $clean_tags = array_filter($snippettag_id); if (!empty($clean_tags)) { foreach($clean_tags as $tag) { $this->db->or_like('snippets_name', "|{$tag}|"); } } else { // Optional: Handle empty tag set (e.g., return no results) $this->db->where('1', '0'); }
Why This Works
array_filterstrips out all empty strings, so you only work with actual tag values.- Wrapping each tag in
|ensures your query targets%|tag|%, which will only match the exact tag enclosed in pipes—so searching for "sql" won’t accidentally match "MySQL".
Content of the question originates from Stack Exchange, question author Hitesh Chauhan
相关产品推荐
相关产品推荐

