phpregexregex-groupregexp-replace

regex just take last value


my problem is when regex get any value it just take last correct one

input

Mozilla/5.0 (Windows Phone 10.0; Android 6.0.1; SAMSUNG; GT-I8750) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Mobile Safari/537.36 Edge/15.15063

output i get

Android

what real output i want

Windows Phone 10.0

my code

function getOS() { 
  global $user_agent;
  $os_platform    = "Unknown OS Platform";
  $os_array       = array(
'/Windows Phone 10.0/i'         =>  'Windows Phone 10',
'/android/i'            =>  'Android',

    );

foreach ($os_array as $regex => $value) { 
  if (preg_match($regex, $user_agent)) {
    $os_platform  = $value;
  }
}

return $os_platform;
}

it replace with last correct match he's get... i just want take "Windows Phone 10.0" even if it find "Android" in my input.

thanks


Solution

  • The issue you're facing is that the code is overwriting the $os_platform variable with the last match found in the $os_array. To achieve your desired result, you can modify your code to stop searching once a match is found.

    function getOS(userAgent) {
      let osPlatform = "Unknown OS Platform";
      const osArray = [
        { regex: /Windows Phone 10\.0/i, value: 'Windows Phone 10' },
        { regex: /android/i, value: 'Android' }
      ];
    
      for (const item of osArray) {
        if (item.regex.test(userAgent)) {
          osPlatform = item.value;
          break; // Stop searching once a match is found
        }
      }
    
      return osPlatform;
    }
    
    const userAgent = "Mozilla/5.0 (Windows Phone 10.0; Android 6.0.1; SAMSUNG; GT-I8750) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Mobile Safari/537.36 Edge/15.15063";
    const os = getOS(userAgent);
    console.log(os); // Output: "Windows Phone 10"