【问题标题】:Boolean Search Processing in PHP for PostgreSQLPHP for PostgreSQL 中的布尔搜索处理
【发布时间】:2011-09-25 23:41:51
【问题描述】:

这似乎是一个显而易见的问题,但目前似乎没有任何答案。

我正在尝试使用 PHP 处理搜索查询以进入具有正确格式的 postgresql 全文搜索。我是正则表达式的新手,我似乎不知道从哪里开始。

我希望按照Something AND ("Some Phrase" OR Some Other Phrase) 进行查询并将其转换为'Something' & (('Some' & 'Phrase')|('Some' & 'Other' & 'Phrase'))

您也许可以将我指向执行此操作的库,尽管我认为这是一个常见问题,但我似乎找不到。感谢您的帮助!

【问题讨论】:

    标签: php regex postgresql search full-text-search


    【解决方案1】:

    此代码将解析给定的示例并返回请求的输出。请注意,它有些脆弱:您可能需要验证表达式的格式以确保它与您发布的格式相似。

    $input = 'Something AND ("Some Phrase" OR Some Other Phrase)';
    
    $formatted_output = format_input( $input );
    
    // Convert a query to a format suitable for a Postgres full-text search
    function format_input( $input ) {
        $output = '';
        list ( $part1, $part2 ) = explode( 'AND', $input );
    
        // Remove any unecessary characters and add the first part of the line format
        $output = "'" . str_replace( array( "\"", "'" ), '', trim( $part1 ) ) . "' & (";
    
        // Get a list of phrases in the query
        $phrases = explode( 'OR', str_replace( array( '(', ')'), '', $part2 ) );
    
        // Format the phrase
        foreach ( $phrases as &$phrase ) {
            $phrase = encapsulate_phrase( trim ( str_replace( array( "\"", "'"), '', $phrase ) ) );
        }
    
        // Add the formatted phrases to the output
        $output .= '(' . implode( ')|(', $phrases ) . ')';
    
        // Add the closing parenthesis
        $output .= ')';
    
        return $output;
    }
    
    // Split a search phrase into words, and encapsulate the words
    function encapsulate_phrase( $phrase ) {
        $output = '';
        $words = explode( ' ', trim( $phrase ) );
    
        // Remove leading and trailing whitespace, and encapsulate words in single quotes
        foreach ( $words as &$word ) {
            $word = "'" . trim( $word ) . "'";
        }
    
        // Add each word to the output
        $output .= implode (" & ", $words);
    
    
        return $output;
    }
    

    您可以像这样测试您的输入:

    $desired_output = "'Something' & (('Some' & 'Phrase')|('Some' & 'Other' & 'Phrase'))";
    
    if ( !assert ( $formatted_output == $desired_output ) ) {
        echo "Desired: $desired_output\n";
        echo "Actual:  $formatted_output\n";
    }
    else {
        echo "Output: $formatted_output\n";
    }
    

    【讨论】:

    • 谢谢乔治,这当然让我开始了。需要让它更通用一点,但这给了我很大的先机!
    猜你喜欢
    • 2012-05-06
    • 2013-05-30
    • 2017-01-24
    • 2014-03-30
    • 2012-09-21
    • 1970-01-01
    • 2023-03-30
    • 1970-01-01
    • 2021-07-08
    相关资源
    最近更新 更多