简体   繁体   English

在SphinxSE中转义特殊字符

[英]Escaping special characters in SphinxSE

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: 我使用sphinx存储引擎实现在我的网站上搜索,效果相当不错,但是当搜索包含诸如&和@之类的字符时,搜索失败并出现以下错误:

There was a problem processing the query on the foreign data source. Data source error: search query already specified

and php throws this error: 和PHP抛出此错误:

Warning: mysql_query() [function.mysql-query]: Unable to save result set in /home/path/to/file.php on line 100

Im escaping the user's input with mysql_real_escape_string 我用mysql_real_escape_string转义用户的输入

Whats interesting is if I copy the query and run it in phpmyadmin directly, I get no errors. 有趣的是,如果我复制查询并直接在phpmyadmin中运行它,我没有错误。

 query = '@title("cheese & cake");limit=1000filter=type=1;ranker=sph04;mode=extended;sort=extended:@weight desc;'

Character escaping in Sphinxql is a tricky subject... I'm not sure if it is fully officially resolved. Sphinxql中的字符转义是一个棘手的主题...我不确定它是否完全正式解决。 mysql_real_escape_string won't handle the special Sphinx query characters. mysql_real_escape_string不会处理特殊的Sphinx查询字符。

They do provide an escape function in sphinxapi.php: 它们确实在sphinxapi.php中提供了一个转义函数:

function EscapeString ( $string )
{
    $from = array ( '\\', '(',')','|','-','!','@','~','"','&', '/', '^', '$', '=' );
    $to   = array ( '\\\\', '\(','\)','\|','\-','\!','\@','\~','\"', '\&', '\/', '\^', '\$', '\=' );
    return str_replace ( $from, $to, $string );
 }

Note that this won't specifically handle the SQL escape characters (for example, no single quote replacement). 请注意,这不会专门处理SQL转义字符(例如,没有单引号替换)。 Actually, I tested it, and it doesn't even work just for Sphinx characters. 实际上,我测试了它,它甚至不适用于Sphinx角色。

You need this function: 你需要这个功能:

function EscapeSphinxQL ( $string )
{
    $from = array ( '\\', '(',')','|','-','!','@','~','"','&', '/', '^', '$', '=', "'", "\x00", "\n", "\r", "\x1a" );
    $to   = array ( '\\\\', '\\\(','\\\)','\\\|','\\\-','\\\!','\\\@','\\\~','\\\"', '\\\&', '\\\/', '\\\^', '\\\$', '\\\=', "\\'", "\\x00", "\\n", "\\r", "\\x1a" );
    return str_replace ( $from, $to, $string );
}

Note the extra backslashes on the Sphinx-specific characters. 请注意Sphinx特定字符上的额外反斜杠。 I think what happens is that they put your whole query through an SQL parser, which removes escape backslashes 'extraneous' for SQL purposes (ie '\\&' -> '&'). 我认为发生的事情是他们将整个查询通过一个SQL解析器,它为SQL目的删除了逃避反斜杠的“无关”(即'\\&' - >'&')。 Then, it puts the MATCH clause through the fulltext parser, and suddenly '&' is a special character. 然后,它将MATCH子句放入全文解析器,突然'&'是一个特殊字符。 So, you need the extra backslashes in the beginning. 因此,您需要在开头添加额外的反斜杠。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM