我想制作一个产品搜索引擎,用户在其中输入产品代码,它会带回结果,这很容易。
但是,我希望能够补偿看起来像字母的数字,反之亦然。
例如,用户键入 6O12l,但产品代码实际上是 60121。
我需要在 SQL 查询中输入什么才能恢复所有带有 6O12l 和/或 60121 的产品?
到目前为止,我
有这个不起作用,无论我输入什么,它每次都会返回相同的结果:
$searchString = $_POST['query'] ;
$searchString = preg_replace('#'W#', '', $searchString);
$firstLetter = substr($searchString, 0, 1) ;
include("db.php") ;
$result = $dbh->prepare("SELECT productCode
FROM products
WHERE productCodeREGEXP '6[O0]12[1l]'
AND productCode LIKE '$firstLetter%'") ;
$result->execute() ;
while($row = $result->fetch(PDO::FETCH_ASSOC)) {
echo $row['productCode'].'<br />' ;
}
我已经设法让它工作,但我遇到了一个新问题。
我正在使用str_replace来替换用户查询字符串中的数字和viceversa的字母,但它仅适用于其中一个,而不适用于两者:
$qString = str_replace(array('o', 'l', '0', '1'), array('[O0]', '[1l]', '[O0]', '[1l]'), $searchString) ;
这给了我一个混乱的输出,例如 A[[1l]l]BC而不是 A[1l]BC
你有带字母的产品代码吗? 在运行查询之前,可以将查询字符串转换为所有数字。 这是最简单的事情,并且比测试两者要快得多。
您无法使用正则表达式有效地搜索数据库。但是,您可以以规范化形式转换要存储的数据,并使用规范化查询字符串进行搜索,例如将所有O
转换为零,I
和l
转换为 1 等。
使用这个:
SELECT * from products
where code REGEXP '6[O0]12[1l]'
我解决了它:D
作为参考,我在 PHP.net 上找到了这个函数:
function search_replace($s,$r,$sql)
{ $e = '/('.implode('|',array_map('preg_quote', $s)).')/';
$r = array_combine($s,$r);
return preg_replace_callback($e, function($v) use ($s,$r) { return $r[$v[1]]; },$sql);
}
另一种选择
// regex expresssion
// str_replace goes in order, first change letters to numbers, then change to the regex
// 6012ol becomes 6[0O][1l]2[0O][1l]
$regexString = str_replace(array('o', 'l', '0', '1'), array('0', '1', '[0O]', '[1l]'), $searchString);
// like expression, allows the database to make the initial filter, _ is the single character match
// 6012ol becomes 6__2__
$likeString = str_replace(array('o', 'l', '0', '1'), '_'), $searchString);
$filt1 = "(productCode LIKE '$likeString%')"; // last % allows for partial matches
$filt2 = "(productCode REGEXP '$regexString')";
// now query, with the like filter first
$dbh->prepare("SELECT productCode
FROM products
WHERE $filt1 AND $filt2
") ;