Renz Daitol
Renz Daitol

Reputation: 17

how to compare php regular expression output to a string in a switch function?

I have this string "test1.base-loc.com" which is the value inside the argument $baseURL. I'd like to get the "test1" using RegEx and compare the output to match to the given cases in my switch function. How can I do that properly?

    private function getAppID($baseURL){
    $re = '/(\w)*/m';
    $str = $baseURL;
    $to_return;

    preg_match($re, $str, $matches, PREG_OFFSET_CAPTURE);

    switch($matches[0]){
        case 'test1':
        $to_return = 2;
        break;

        case 'test2':
        $to_return = 3;
        break;

        case 'test3':
        $to_return = 4;
        break;

        case 'test4':
        $to_return = 5;
        break;

        default:
        $to_return = 1;
        break;
    }
    return $to_return;
}

Upvotes: 0

Views: 83

Answers (2)

ggorlen
ggorlen

Reputation: 57115

switch($matches[0][0]) does the trick. The extra index is necessary as a var_dump() of $matches reveals:

array(2) {
  [0]=>
  array(2) {
    [0]=>
    string(5) "test1"
    [1]=>
    int(0)
  }
  [1]=>
  array(2) {
    [0]=>
    string(1) "1"
    [1]=>
    int(4)
  }
}

As others point out, this is probably not the ideal way to solve the problem, though. There are many other ways, for example:

preg_match('/test([1-4])\./', $baseURL, $m);
return $m ? $m[1] + 1 : 1;

Upvotes: 0

Spoody
Spoody

Reputation: 2882

In my opinion an explode with an array is way shorter and cleaner

private function getAppId($url)
{        
    $subdomain = explode('.', $url);

    $ids = [
        'test1' => 2,
        'test2' => 3,
        'test3' => 4,
        'test4' => 5,
    ];

    // Return the ID if it exists or 1
    return $ids[$subdomain[0]] ?? 1;
}

Be aware that this will get sub in sub.test.domain.com, so this is not the best way to parse a URL, only use this if you are 100% sure that the input is going to be sub.domain.com or this won't work.

The ?? is the null coalescing operator it was introduced in PHP 7

Upvotes: 1

Related Questions