Domanda

I have a list of Mobile devices that I'm using to display content correctly. The depreciated function looks like this:

function detectPDA($query){
    $browserAgent = $_SERVER['HTTP_USER_AGENT'];
    $userAgents = $this->getBrowserAgentsToDetect(); // comma separated list of devices
    foreach ( $userAgents as $userAgent ) {
        if(eregi($userAgent,$browserAgent)){
            if(eregi("iphone",$browserAgent) || eregi("ipod",$browserAgent) ){
                $this->iphone = true;
            }else{
                $this->pda = true;
            }
        }
    }
}

What is the correct way to replace the eregi functions?

È stato utile?

Soluzione

If all the pattern strings ($userAgent and iphone) can be trusted not to contain special regex chars (()[]!|.^${}?*+), then you just surround the eregi regex with slashes (/) and add an i after the last slash (which means "case insensitive").

So:

eregi($userAgent,$browserAgent) --> preg_match("/$userAgent/i",$browserAgent)
eregi("iphone",$browserAgent)   --> preg_match('/iphone/i',$browserAgent)

However, are you just trying to match $userAgent as-is within $browserAgent? For example, if a particular $userAgent was foo.bar, would you want the . to match a literal period, or would you want to interpret it in its regex sense ("match any character")?

If the former, I'd suggest you forgo regex entirely and use stripos($haystack,$needle), which searches for the string $needle in $haystack (case-insensitive). Then you don't need to worry about (say) an asterisk in $userAgent being interpreted in the regex sense instead of the literal sense.

If you do use stripos don't forget it can return a 0 which would evaluate to false, so you need to use === false or !== false (see the documentation I linked).

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top