这是我从表单输入的post方法。表单包括搜索技术。What are the difference between AC motor and DC motor?
我希望输出是What|difference|AC|motor|DC|motor
但是我得到了输出What|||difference||AC|motor||DC|motor
我做错什么了?
这是我的编码方法
<?php
include 'dbh.inc.php';
if(isset($_POST['submit']) && !empty($_POST['search'])){
$value = trim(mysqli_real_escape_string($conn, $_POST['search']));
$noSpace = preg_replace('/\s+/', ' ', $value);
$noCommon = removeCommonWords($noSpace);
$replace = str_replace(' ', '|', $noCommon);
echo $replace;
}
function removeCommonWords($input){
// EEEEEEK Stop words
$commonWords = array('a','able','about','above','abroad',..........);
return preg_replace('/\b('.implode('|',$commonWords).')\b/','',$input);
}
?>
最佳答案
您可以匹配和跳过常用词,只匹配和保留其他词块:
\b(?:are|the|between|and)\b(*SKIP)(*F)|\w+
请参见regex demo。
详情
\b(?:are|the|between|and)\b
-整词are
等。(*SKIP)(*F)
-放弃匹配并从不成功匹配的结尾继续查找下一个匹配的pcre动词|
-或\w+
-只需匹配并保留一个或多个单词字符。这里有一个PHP snippet:
$commonWords = ['are','the','between','and'];
$value = 'What are the difference between AC motor and DC motor?';
$rx = '~\b(?:' . implode('|', $commonWords) . ')\b(*SKIP)(*F)|\w+~u';
if (preg_match_all($rx, $value, $matches)) {
echo implode('|', $matches[0]); // => What|difference|AC|motor|DC|motor
}
关于php - PHP MySQL中的多个关键字搜索,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51230773/