Curtis Boylan
Curtis Boylan

Reputation: 827

Preg_match only working in order

I am having problems with the following code. I am getting the users subjects using $_GET then sending it to the server to see if the row contains the subjects and if it does then it returns subject matches row for each row it matches. This currently works fine but if the user enters lets say "english,maths" and in the database it is listed as "maths, english" it will fail and will not echo that row although it is correct just in a different order. Is there anything I am doing wrong??

Thanks,

CurtisB

    $subjects = $_GET["subjects"];  
    while ($row = mysql_fetch_array($result, MYSQL_ASSOC) and ($counter < $max)) 
    {
       if(preg_match('/'.$subjects.'/',$row['subjects'])){
       echo "subject matches row";         
        }
    }

UPDATE: Tried code below, which is echoing every row even if not the correct subject.

 function is_matched($subjectsFromUs, $subjectsFromDb){
        $subjectsFromUs = explode($subjectsFromUs, ',');
        $subjectsFromDb = explode($subjectsFromDb, ',');
        foreach($subjects as $s){
            if(!in_array($s, subjectsFromDb))
                return false;
        }
        return true;
    } 

while ($row = mysql_fetch_array($result, MYSQL_ASSOC) and ($counter < $max)) 
{
   if(is_matched($subjects,$row['subjects']) == true ){

echo "subjects matched";
}
}

Upvotes: 0

Views: 38

Answers (1)

nikit
nikit

Reputation: 153

I think that you shouldn't use regexp in such a case. You must just explode your $subjects parameter by ',' and traverse that array trough $row['subjects']:

  function is_matched($subjects, $subjectsFromDb){
        $subjects = explode(',', $subjects);
        $subjectsFromDb = explode(',', $subjectsFromDb);
        foreach($subjects as $s){
            if(!in_array($s, $subjectsFromDb))
                return false;
        }
        return true;
    }

Upvotes: 1

Related Questions