3

Actaully I have to search a input value from a txt file, when keydown event is triggered (it means the search function take place as alphabetically). That txt file has multiple lines and keys.

Now firstly let me describe the whole scenario with appropriate code.

HTML Code:

    <input type="text" name="searchval" /> 
    <div></div>

    $(document).ready(function(){
      $('input').bind('keydown',function(){
        setTimeout(search($(this).val().toLowerCase()),2000);
      });
    });

    function search(v){
      $.ajax({
        url:'search.php',
        type:'get',
        data:'sv='+v,
        dataType:'json',
        cache:false,
        success:function(r){$('div').empty();for(var i in r){$('div').append(r[i]+",");}},
        error:function(a,b,c){$('body').append(b+'<hr/>');}
      });
    }

PHP Code:

  //ADD DATA TO TXT FILE
  $file = "UL.txt";
  if((!file_exists($file)) || (0 == filesize($file))){
    $data = "$name|$email|Offline";
  }else{
    $data = "\r\n$name|$email|Offline";
  }
  $fp = fopen("UL.txt", "a") or die("Couldn't open file for writing!");
  fwrite($fp, $data) or die("Couldn't write values to file!"); 
  fclose($fp);

`UL.txt'

  Abc Def|abc@def.com|Offline
  Ghi Jkl|ghi@jkl.com|Offline
  Mno Pqr|mno@pqr.com|Offline
  Stu Vwxyz|stuv@wxyz.com|Offline
  ....

search.php:

    header('Content-Type: application/json');
    $search = array();
    if($_SERVER["REQUEST_METHOD"] == "GET"){
      $searchMe = $_GET['sv'];
      $F = file("UL.txt");
      foreach($F as $k1 => $v1) { 
        $d1[$k1] = explode("|", $v1);
        $email[] = strtolower(trim($d1[$k1][1])); //$d1[$k1][1];
        $name[] = strtolower(trim($d1[$k1][0])); //$d1[$k1][0];
        foreach($email as $k2 => $v2){
          if($v2 == $searchMe){
            $search[] = $v2; 
          }else{
            $search = 'NO RESULT';
          }
        }
      }
    }
    echo json_encode($search);

Now, this code doesn't work.

Instead of $v2, $search[] must return the name:email:status IF $searchMe matchs $email or $name, but I don't know how to do this. Means how to match words by words and use the keys to assign the whole line to the $search[].

Thanks & Regards.

1 Answers1

2

If you want to search between the exploded string (name, and email) why not use stripos()?

Sample code:

<?php

$data = array();
$return_value = array();

if($_SERVER["REQUEST_METHOD"] == "GET") {
    $needle = strtolower(urlencode($_GET['sv']));
    $file_contents = file('ul.txt');
    sort($file_contents);
    $range = strlen($needle);

    foreach($file_contents as $key => $haystack) {
        $smaller_haystack = explode('|', $haystack);
        // search for name or email
        $remove_dot_com = str_replace('.com', '', $smaller_haystack[1]);
        // if(stripos($smaller_haystack[0], $needle) !== false || stripos($remove_dot_com, $needle) !== false) {
       if((substr(strtolower($smaller_haystack[0]), 0, $range)) == $needle || (substr($remove_dot_com, 0, $range)) == $needle) {
            $return_value[$key]['name'] = $smaller_haystack[0];
            $return_value[$key]['email'] = $smaller_haystack[1];
            $return_value[$key]['status'] = $smaller_haystack[2];
        }
    }

    echo json_encode($return_value);
}

?>

and then just append results on html:

Search: <input type="text" name="search" id="search_field" />
<table id="search_results"></table>

$('#search_field').keyup(function(e){
    var search_value = $(this).val();
    $.ajax({
        url: 'results.php?sv=' + encodeURIComponent(search_value),
        type: 'GET',
        dataType: 'json',
        success: function(response) {
        $('#search_results').empty();
            $.each(response, function(index, element){
                $('#search_results').append('<tr><td>'+element.name+' - ' + element.email + ' - ' + element.status + '</td></tr>');
            });
        }
    });

});
user1978142
  • 7,946
  • 3
  • 17
  • 20
  • Thanks Dear, its words perfectly. But I want to know one thing, that `stripos()` is reliable or not, if `txt` file has thousands of line? – Nikita Chaudhary Apr 22 '14 at 07:24
  • 1
    with regards to performance (statistical data), i cannot provide one, but you can also search for benchmarks on google or you can also check this one [here](http://stackoverflow.com/questions/5821483/what-is-the-fastest-way-to-find-the-occurrence-of-a-string-in-another-string). – user1978142 Apr 22 '14 at 07:26
  • One more thing, It return all matching values, like, if i'm searching for `de`, than it returns all values that contains `de`. But at this scenario, it should match and returns `key line` based on the `starting alphabets` only. – Nikita Chaudhary Apr 22 '14 at 07:29
  • 1
    if you want to only check the starting alphabet you can just change the condition to `substr()` instead of `stripos()`, check my edit – user1978142 Apr 22 '14 at 07:42
  • :) Its only works when `single alphabet` is entered. If `more than one` alphabets are entered, than :) `, 0, 1` – Nikita Chaudhary Apr 22 '14 at 07:54
  • i edited code so that it can dynamically accomodate more than one alphabet – user1978142 Apr 22 '14 at 08:08