我从w3schools找到了这个代码(不要评判我)。
aspphp.asp
这是一个代码,允许您创建一个类似于Google使用AJAX的搜索字段。
代码工作正常,但是在我的.php中字符串超过一个字,只有在搜索第一个单词时,它才能正确地输出。如果我试图在输入字段中放置字符串中的任何内容,它就不会输出。例如,我的字符串可能是:
$a[]="This is string 1."
$a[]="This is string 2."
$a[]="Is this string 3?"
$a[]="Is this string 4?"问题是,如果我输入“This”,它只会显示从这个开始的结果。如果我放“string”,它会说没有结果。有什么想法吗?我确信问题在PHP部分中:
$q=$_REQUEST["q"]; $hint="";
if ($q !== "")
{ $q=strtolower($q); $len=strlen($q);
foreach($a as $name)
{ if (stristr($q, substr($name,0,$len)))
{ if ($hint==="")
{ $hint=$name; }
else
{ $hint .= "<br>$name"; }
}
}
}
// Output "no suggestion" if no hint were found
// or output the correct values
echo $hint==="" ? "Refine search values" : $hint;
?>发布于 2014-07-21 00:09:54
您应该再次阅读有关stristr()的文档,特别是参数的顺序:
string stristr(string $haystack , mixed $needle [, bool $before_needle = false ])所以你的台词
if (stristr($q, substr($name,0,$len)))实际上应该是
if (stristr($name, $q))由于您不使用stristr()返回的字符串,所以最好使用stripos()
if (stripos($name, $q) !== FALSE)如果字符串应该支持Unicode,则将str*函数替换为它们匹配的mb_str*函数。
发布于 2014-07-21 00:09:23
问题是,您所拥有的代码没有检查整个字符串。相反,您的函数(实际上是ww3schools)只查找以相同字符开头的数组中的值。
您想要做的是自己创建一个可以进行“关键字”搜索的功能。我将由您来决定如何使用这个函数:
if (strpos($str, $cont) !== FALSE)Strpos检查$str的值是否为$cont,如果它包含该单词,则返回true。
发布于 2014-07-21 00:10:24
这个问题正在发生,因为这一行。
substr($name, 0, $len)只匹配字符串开头的a[]内容。
你的代码应该是
if ($q !== "")
{ $q=strtolower($q); // not needed //$len=strlen($q);
foreach($a as $name)
{ if (stristr($name, $q))
{ if ($hint==="")
{ $hint=$name; }
else
{ $hint .= "<br>$name"; }
}
}
}https://stackoverflow.com/questions/24856055
复制相似问题