Search code examples
phparrayscsvsearchpartial

Partial match search of an array (CSV FILE)


I want to have partial search on my CSV file. Here is a sample:

order1223445, DemoName1, MyLocal Address 1, R123456789

order12235443, DemoName2, MyLocal Address2 , W123456789

order1223254, DemoName3, MyLocal Address 3, T123456789

I was able to search it on exact word but not in partial

while($row = fgetcsv($ch)) {

    if (in_array($regValue, $row)) {
        echo '<div>' . implode(' | ', $row) . ' </div>';
    }
}

So if I input order1223445 it will show the whole row.

order1223445, DemoName, MyLocal Address, 123456789

But if I input order122 or mylocal

Nothing is shown


Solution

  • using preg_match could be a solution.

    while($row = fgetcsv($ch)) {
    
        $matched = FALSE;
    
        foreach ($row as $column){
    
            $regular_expression = sprintf("/%s/",$regValue);
    
            if (preg_match($regular_expression,$column)){
                $match=TRUE;
            }      
        }
    
        if ($match) {
            echo '<div>' . implode(' | ', $row) . ' </div>';
        }
    }