phpregexsymfonygetsymfony-http-foundation

Get both fields from url and convert them to variables to query a search


I am trying to get both fields in an api enpoint so that it queries based on that. example.

api/evenSession/123123123/eventSession?token=1234656&filter= chris moreno

my controller searches by first or last name. But i want to create an endpoint that it queries the database if it's passed in "chris moreno"

This is my $filter code

if(preg_match_all('/^[A-Z]*[a-z]*(-|\s)[A-Z]*[a-z]*$/', $filter)){
       $searchFields = [
           'a.lastName',
           'a.firstName'
       ];

I'd like to be able to catch both fields (chris and moreno) in my filter so that I can pass that over to my query so that it can check for people checked in with first and last name (narrow the search)


Solution

  • Here, we would have three capturing groups, if our inputs are as listed, for instance, an expression we would start with:

    token=(.*?)&filter=\s*([\w]+)\s+([\w]+)
    

    Demo 1

    Here, we our token value in this capturing group:

    (.*?)
    

    and our names in these two separate capturing groups:

    ([\w]+)
    

    which the last two groups can be modified, if we have names such as O'Neal, that may not fall into [A-Za-z] char class. For instance, we can allow any chars:

    token=(.*?)&filter=\s*(.+?)\s+(.+) 
    

    Demo 2

    Test

    $re = '/token=(.*?)&filter=\s*([\w]+)\s+([\w]+)/m';
    $str = 'api/evenSession/123123123/eventSession?token=1234656&filter= chris moreno
    api/evenSession/123123123/eventSession?token=1234656&filter= alice bob
    ';
    
    preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);
    
    $searchFields = [];
    foreach ($matches as $key => $value) {
        $searchFields[$key] = [$value[2], $value[3]];
    }
    
    var_dump($searchFields);
    

    Demo 3