Skip to content

Commit

Permalink
like转义
Browse files Browse the repository at this point in the history
  • Loading branch information
lisijie committed May 31, 2018
1 parent 777c4a1 commit 91b8370
Showing 1 changed file with 23 additions and 4 deletions.
27 changes: 23 additions & 4 deletions src/Core/Model.php
Original file line number Diff line number Diff line change
Expand Up @@ -349,22 +349,26 @@ protected function parseFilter(array $filter)
$val = [$val];
}
foreach ($val as $k => $v) {
$where[] = "`{$field}` LIKE " . $this->db->quote("%{$v}%");
$v = $this->escapeLike($v);
$where[] = "`{$field}` LIKE '%{$v}%'";
}
break;
case 'notlike': //NOT LIKE ‘%%’, 支持多个
if (!is_array($val)) {
$val = [$val];
}
foreach ($val as $k => $v) {
$where[] = "`{$field}` NOT LIKE " . $this->db->quote("%{$v}%");
$v = $this->escapeLike($v);
$where[] = "`{$field}` NOT LIKE '%{$v}%'";
}
break;
case 'startswith': //LIKE 'xxx%'
$where[] = "`{$field}` LIKE " . $this->db->quote("{$val}%");
$val = $this->escapeLike($val);
$where[] = "`{$field}` LIKE '{$val}%'";
break;
case 'endswith': //LIKE '%xxx'
$where[] = "`{$field}` LIKE " . $this->db->quote("%{$val}");
$val = $this->escapeLike($val);
$where[] = "`{$field}` LIKE '%{$val}'";
break;
case 'between': //between 'a' AND 'b'
$where[] = "(`{$field}` BETWEEN " . $this->db->quote($val[0]) . " AND " . $this->db->quote($val[1]) . ")";
Expand Down Expand Up @@ -403,6 +407,21 @@ protected function parseFilter(array $filter)
return implode(' AND ', $where);
}

/**
* like转义
*
* @param $string
* @return string
*/
private function escapeLike($string)
{
if (empty($string)) {
return $string;
}
$string = strtr($string, ['\\' => '\\\\']);
return strtr(substr($this->db->quote($string), 1, -1), ['%' => '\%', '_' => '\_']);
}

/**
* 字段解析成SQL
*
Expand Down

0 comments on commit 91b8370

Please sign in to comment.