Connecting Tech Pros Worldwide Help | Site Map

conditional preg match

toedipper
Guest
 
Posts: n/a
#1: Sep 29 '05
Hello,

The following bit of code does a preg match and does something if true
(sets $browser to ppcie)

Without using if then and else's how do I code it so it does not equal
what it is testing for? So if it does not find ppc in the $agent then
it does something else/sets it to something else?

$agent = getenv("HTTP_USER_AGENT");
if (preg_match("/PPC/i", "$agent")) {
$browser = 'PPCIE';
}

Thanks,

td.
www.pocketpcheaven.com
Oli Filth
Guest
 
Posts: n/a
#2: Sep 30 '05

re: conditional preg match


toedipper said the following on 29/09/2005 21:49:[color=blue]
> Hello,
>
> The following bit of code does a preg match and does something if true
> (sets $browser to ppcie)
>
> Without using if then and else's how do I code it so it does not equal
> what it is testing for? So if it does not find ppc in the $agent then
> it does something else/sets it to something else?
>
> $agent = getenv("HTTP_USER_AGENT");
> if (preg_match("/PPC/i", "$agent")) {
> $browser = 'PPCIE';
> }
>[/color]

What on earth's wrong with if/else?

But alternatively:

$browser = (preg_match(...)) ? 'PPCIE' : 'something else';


--
Oli
Hero Wanders
Guest
 
Posts: n/a
#3: Sep 30 '05

re: conditional preg match


Hello!
[color=blue]
> preg_match("/PPC/i", "$agent")[/color]
^ ^

IMO you should use >$agent< instead of >"$agent"<.
Furthermore you are only doing a check whether one string is in another.
Use stripos (PHP5), strpos in combinanation with strtolower or stristr
for this.
IIRC the second is the fastest for PHP4.

if (strpos(strtolower($agent), 'ppc') !== false) {
// ...
}

http://php.net/strpos
http://php.net/stripos
http://php.net/strstr
http://php.net/stristr
http://php.net/strtolower

Greetings,
Hero Wanders
Closed Thread


Similar PHP bytes