在SphinxSE中转义特殊字符 [英] Escaping special characters in SphinxSE
问题描述
我使用sphinx存储引擎实现在我的网站上进行搜索,效果很好,但是当搜索包含诸如&和@,搜索失败,并显示以下错误:
Im using sphinx storage engine implementation for searching on my site, which works fairly well, however when a search includes characters such as & and @, the search fails with the following error:
There was a problem processing the query on the foreign data source. Data source error: search query already specified
并且php引发此错误:
and php throws this error:
Warning: mysql_query() [function.mysql-query]: Unable to save result set in /home/path/to/file.php on line 100
使用mysql_real_escape_string
有趣的是,如果我复制查询并直接在phpmyadmin中运行它,则不会出错.
Whats interesting is if I copy the query and run it in phpmyadmin directly, I get no errors.
query = '@title("cheese & cake");limit=1000filter=type=1;ranker=sph04;mode=extended;sort=extended:@weight desc;'
推荐答案
在Sphinxql中转义字符是一个棘手的问题……我不确定它是否已完全正式解决. mysql_real_escape_string无法处理特殊的Sphinx查询字符.
Character escaping in Sphinxql is a tricky subject... I'm not sure if it is fully officially resolved. mysql_real_escape_string won't handle the special Sphinx query characters.
它们确实在sphinxapi.php中提供了转义功能:
They do provide an escape function in sphinxapi.php:
function EscapeString ( $string )
{
$from = array ( '\\', '(',')','|','-','!','@','~','"','&', '/', '^', '$', '=' );
$to = array ( '\\\\', '\(','\)','\|','\-','\!','\@','\~','\"', '\&', '\/', '\^', '\$', '\=' );
return str_replace ( $from, $to, $string );
}
请注意,这不会专门处理SQL转义字符(例如,没有单引号替换).实际上,我已经对其进行了测试,它甚至不仅仅适用于Sphinx字符.
Note that this won't specifically handle the SQL escape characters (for example, no single quote replacement). Actually, I tested it, and it doesn't even work just for Sphinx characters.
您需要此功能:
function EscapeSphinxQL ( $string )
{
$from = array ( '\\', '(',')','|','-','!','@','~','"','&', '/', '^', '$', '=', "'", "\x00", "\n", "\r", "\x1a" );
$to = array ( '\\\\', '\\\(','\\\)','\\\|','\\\-','\\\!','\\\@','\\\~','\\\"', '\\\&', '\\\/', '\\\^', '\\\$', '\\\=', "\\'", "\\x00", "\\n", "\\r", "\\x1a" );
return str_replace ( $from, $to, $string );
}
请注意在狮身人面像特定字符上的额外反斜杠.我认为发生的事情是,他们将整个查询通过SQL解析器进行处理,该解析器出于SQL的目的(即'\&'->'&')删除了转义的反斜杠.然后,它将MATCH子句放在全文分析器中,然后突然出现&"是一个特殊字符.因此,您需要在开始时添加额外的反斜杠.
Note the extra backslashes on the Sphinx-specific characters. I think what happens is that they put your whole query through an SQL parser, which removes escape backslashes 'extraneous' for SQL purposes (i.e. '\&' -> '&'). Then, it puts the MATCH clause through the fulltext parser, and suddenly '&' is a special character. So, you need the extra backslashes in the beginning.
这篇关于在SphinxSE中转义特殊字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!