此代码将解析给定的示例并返回请求的输出。请注意,它有些脆弱:您可能需要验证表达式的格式以确保它与您发布的格式相似。
$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";
}