2017-11-11 121 views
1

我需要一些帮助来完善我目前的搜索。Ajax搜索POST到php

我有一个图片文件夹命名为:

20171116-category_title.jpg  (where first number is date yyyymmdd) 

我目前的搜索是这样的:

<?php 
// string to search in a filename. 

if(isset($_POST['question'])){ 
    $searchString = $_POST['question']; 
} 
// image files in my/dir 
$imagesDir = ''; 
$files = glob($imagesDir . '*.{jpg,jpeg,png,gif}', GLOB_BRACE); 

// array populated with files found 
// containing the search string. 
$filesFound = array(); 

// iterate through the files and determine 
// if the filename contains the search string. 
foreach($files as $file) { 
    $name = pathinfo($file, PATHINFO_FILENAME); 

    // determines if the search string is in the filename. 
    if(strpos(strtolower($name), strtolower($searchString))) { 
     $filesFound[] = $file; 
    } 
} 

// output the results. 
echo json_encode($filesFound, JSON_UNESCAPED_UNICODE); 
?> 

这工作得很好,但...

  1. 我想限制搜索仅限于包含“title”后面的下划线“_”的.jpg名称的一部分,之后(如果可能的话e)将搜索扩展为:

  2. 如果AJAX POST发送以下格式,则进行双重搜索:abc + xyz其中分隔符“+”实际上表示2个查询。

    第一部分是(abc),它只针对查询(xyz)(这基本上是我的第一个问题)的减号和下划线以及第二部分之间的“类别”,仅在之前找到的(类别)答案中。

    您的提示比欢迎! 谢谢!

+0

你解决这个问题,没有我的回答帮助? –

+0

对不起,谢谢你。我离开了我的工作,所以我没有实现你的解决方案,但我看到它会好的。如果因为任何原因我再次被卡住生病如果我可以尝试联系你? 再一次,谢谢你! – vixus

回答

0

对于问题的第一部分,您使用的确切模式取决于您的category字符串的格式。如果你将永远不会有下划线_category,这里有一个解决方案:

foreach($files as $file) { 
    // $name = "20171116-category_title" 
    $name = pathinfo($file, PATHINFO_FILENAME); 

    // $title = "title", assuming your categories will never have "_". 
    // The regular expression matches 8 digits, followed by a hyphen, 
    // followed by anything except an underscore, followed by an 
    // underscore, followed by anything 
    $title = preg_filter('/\d{8}-[^_]+_(.+)/', '$1', $name); 

    // Now search based on your $title, not $name 
    // *NOTE* this test is not safe, see update below. 
    if(strpos(strtolower($title), strtolower($searchString))) { 

如果你的类别可以或将有下划线,你需要调整基于你可以肯定的某种格式的正则表达式。

对于第二个问题,您需要首先将您的查询分解为可寻址的部分。请注意,+通常是如何在URL中对空格进行编码的,因此将它用作分隔符意味着您将永远无法将空间使用搜索词。也许这对你来说不是问题,但如果是这样,你应该尝试另一个分界符,或者更简单的方法是使用单独的搜索字段,例如在搜索表单上输入2个输入。

总之,使用+

if(isset($_POST['question'])){ 
    // $query will be an array with 0 => category term, and 1 => title term 
    $query = explode('+', $_POST['question']); 
} 

现在,在你的循环,你需要找出不只是文件名的$title部分,也是$category

$category = preg_filter('/\d{8}-([^_]+)_.+/', '$1', $name); 
$title = preg_filter('/\d{8}-[^_]+_(.+)/', '$1', $name); 

一旦你拥有了这些,您可以在最终测试中使用它们进行匹配:

if(strpos(strtolower($category), strtolower($query[0])) && strpos(strtolower($title), strtolower($query[1]))) { 

UPDATE

我刚注意到你的匹配测试有问题。 strpos如果在位置0处找到匹配项,则可返回00是一个虚假的结果,这意味着即使有匹配,您的测试也会失败。您需要在FALSE明确测试,as described in the docs

if(strpos(strtolower($category), strtolower($query[0])) !== FALSE 
    && strpos(strtolower($title), strtolower($query[1])) !== FALSE) {