2017-11-11 37 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) {