我制作了简单的PHP代码以在文本文件中进行搜索,
但是我的问题是搜索结果对文本非常敏感,例如,如果我要在“ Iphone 4”上搜索并且文本是“ Iphone4”或“ Iphone-4” 它不会出现在搜索结果中。 我应该添加或修改哪些内容以使其更灵活?
这是我的代码:
<?php
function searchID(Array $array, $value)
{
$idresult = "";
foreach ($array as $subarray){
if (isset($subarray[0]) && (substr($subarray[0], 0, strlen($value)) == $value) && $value!="")
{ $idresult .= $subarray[0]." ".$subarray[2]." ".$subarray[1]."<br />"; }
}
return $idresult;
}
// searchFirstName looks through the given $array and for each item that matches(even partially)
// $value in the first name field it prints a table row of data, also returning a count of found items.
function searchFirstName(Array $array, $value)
{
$firstresult = "";
foreach ($array as $subarray)
{
if (isset($subarray[2]) && stristr($subarray[2],$value) && $value!=""){
$firstresult .= $subarray[0]." ".$subarray[2]." ".$subarray[1]."<br />";
}
}
return $firstresult;
}
function searchLastName(Array $array, $value){
$lastresult = '';
foreach ($array as $subarray){
if (isset($subarray[1]) && stristr($subarray[1],$value) && $value!="") { $lastresult .= $subarray[0]." ".$subarray[2]." ".$subarray[1]."<br />";}
} return $lastresult;
}
$file = fopen("classlist.txt", "r");
$filestring = "";
$line_of_text ="";
while (!feof($file)) {
$tempstring = fgets($file);
$filestring .= $tempstring."<br />";
$line_of_text .= $tempstring;
}
// populate $students array - line by line
$students = explode("\n", $line_of_text);
fclose($file);
// separate the ID, Last name and First name
foreach ($students as $key=>$value){
$students[$key] = explode(",", $value);
}
$term = strip_tags(substr($_POST['search_term'],0, 100));
$string = '';
if ($term != "" && $term != " "){
switch ($_POST['field']) {
case "fname":
$string .= searchFirstName($students, $term);
break;
case "lname":
$string .= searchLastName($students, $term);
break;
case "id":
$string .= searchID($students, $term);
break;
}
}
if ($string != "") echo $string;
else echo '<div class="alert_yellow">No results found</div>';
?>
文本在文本文件中的排序如下:
9810,APPLE_Iphone_4_BW2,pdf
9810,APPLE_Iphone4_BW2,pdf
9810,APPLE_Iphone 4BW2,pdf
9810,APPLE_Iphone_4_BW2,pdf
当我在“ iphone4”上搜索时,结果仅显示“ 9810,APPLE_Iphone4_BW2,pdf”,而不是所有4行!那是我的问题!