Ansehelm
Ansehelm

Reputation: 13

Search through CSV, returning only exact fit value

Again I'm working on a working CSV filter. It will search through about 500 lines of promotional code and return its amount to ajax receiver. The weird thing is, if I only enter 2 letters, instead of searching for exact fit, the php processor would return the result once it has found a value which contains my entered letters! I need it to look for only exact fit of 4-strings value.

Here's my code so far:

<?php
// if data are received via POST, with index of 'test'
if (isset($_POST['test'])) {
    $promocodevalid = false;
    $file  = fopen('test.csv', 'r');
    $coupon = array($_POST['test']); 
    $coupondef = $_POST['test'];             // get data
    $coupon = array_map('preg_quote', $coupon);
    $regex = '/'.implode('|', $coupon).'/i';
    while (($line = fgetcsv($file)) !== FALSE) {  
       list($promocode, $amount) = $line;

       if(preg_match($regex, $promocode)) {
           $validity = 1;
           echo $amount."[BRK]".$promocode."[BRK]".$validity;
           $promocodevalid = true;
           break;
       }
    }
   if(!$promocodevalid) {
       $validity = 0;
       echo $amount."[BRK]".$promocode."[BRK]".$validity;
   }
}
?>   

Upvotes: 0

Views: 375

Answers (1)

Artem L
Artem L

Reputation: 10253

Try to avoid regexes where they are not needed. Search for str* function you need. Above code should look like:

if (isset($_POST['test'])) {
    $promocodevalid = false;
    $file  = fopen('test.csv', 'r');
    $coupondef = $_POST['test'];             // get data

    while (($line = fgetcsv($file)) !== FALSE) {  
       list($promocode, $amount) = $line;  

       // remove strtolower if you are have lowercase promocode, 
       // but probably leave a $coupondef lowered.
       if(strpos(strtolower($promocode), strtolower($coupondef)) === 0) {
           $validity = 1;
           echo $amount."[BRK]".$promocode."[BRK]".$validity;
           $promocodevalid = true;
           break;
       }
    }
   if(!$promocodevalid) {
       $validity = 0;
       echo $amount."[BRK]".$promocode."[BRK]".$validity;
   }
}

Upvotes: 0

Related Questions