mobius2000 mobius2000 - 5 months ago 8
PHP Question

Exclude hyphen from CSV search

hopefully a simple one for someone more experienced than myself.

I am using the following to interogate a CSV file and depending on the search account number, it will bring up info for that account number. This al lworks fine however the auto generated CSV file includes hyphens in the account number however our customers never see this and won't know to seaerch with the hyphen in the number.

Is it possible to complete the same search functionality yet exclude any special characters?

<?php $acctno = isset($_GET['acctno']) ? $_GET['acctno'] : null;

$notices = null;
if ($acctno) {
if ($file = fopen(''.BASE_URL.'/data/ParcelNotices.csv', 'r')) {
while (($data = fgetcsv($file)) !== false) {
if ($data[0] === $acctno) {
$notices = $data[2];
break;
}

}
}
}?>


And my CSv's account numbers look like this: 00100659-05

If they search for 00100659-05 it works perfectly, I need them to be able to enter 0010065905 and get a positive result.

Any help would be greatly appreciated.

Answer

You could modify this part:

if($data[0] === $acctno){
   $notices = $data[2];
   break;
}

To this:

if($data[0] === $acctno || Str_Replace('-','',$data[0])===$acctno)){
   $notices = $data[2];
   break;
}

I believe that would ignore the hyphen when searching. However, if you have a lot of requests, it'd probably be a lot better to create a second copy of your CSV with all the dashes removed, to improve search time.

Edit1: To exclude any non alphanumeric characters, you can use Preg_Replace, like so:

if($data[0] === $acctno || Preg_Replace('@[^a-zA-Z0-9]@','',$data[0])===$acctno)){
   $notices = $data[2];
   break;
}

Edit2: Cleanup:

<?php

//
$acctno_requested = isset($_GET['acctno']) ? $_GET['acctno'] : null;

//
$notices = null;
if ($acctno_requested) {
    if ($file = fopen(''.BASE_URL.'/data/ParcelNotices.csv', 'r')) {
        while (($data = fgetcsv($file)) !== false) {

            //
            $accountno_file=$data[0];
            $accountno_file_clean=Preg_Replace('@[^a-zA-Z0-9]@','',$accountno_file);

            //
            if ($accountno_file_clean === $acctno_requested) {
                $notices = $data[2];
                break;
            } 

        }
    }
}

?>