You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 your or_like clauses match every row (since LIKE "%%" returns all records).
  • You aren’t wrapping tags in pipes within your LIKE condition, 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_filter strips 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 05:17:49