Forum Moderators: coopster

Message Too Old, No Replies

Partial array match instead of only absolute array match?

Match 'Firefox' in example versus having to put full UA in array.

         

JAB Creations

2:58 pm on Jan 5, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I want to serve content to only specific browsers that support a certain technology and I'm trying to build a white list array to do so. However the array only works if I add the exact useragent and does not partially match. So basically I just want to modify the script so that "Firefox" is allowed as a partial match instead of having to use the entire specific useragent string.

- John

<?php
$useragent = $_SERVER['HTTP_USER_AGENT'];

$capable_user_agents = array('Firefox',
'Opera',);
if(!in_array($_SERVER['HTTP_USER_AGENT'],$capable_user_agents))
{
echo 'unsupported technology message here';
}
else {
echo 'supported technology here';
}

jatar_k

3:20 pm on Jan 5, 2007 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



you could do it in a loop and use stristr [php.net] to compare each element in your array to the user agent

Little_G

3:31 pm on Jan 5, 2007 (gmt 0)

10+ Year Member



something like:
[pre]function array_value_in($array,$string){
foreach($array as $elem){
if(strpos($string,$elem)){return true;}
}
}
[/pre]

(case sensitive)

Andrew

JAB Creations

3:36 pm on Jan 5, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



*Edited* (Forgot the add $ to useragent)...still does not work though... */edit*

Here is my guess with stristr though it does not work...

- John

<?php

$useragent = $_SERVER['HTTP_USER_AGENT'];

$useragents = array('Firefox','Opera',);

if (strstr($useragents, $useragent))
{
echo 'your browser is supported';
}
else
{
echo 'fail';
}?>

[edited by: JAB_Creations at 3:50 pm (utc) on Jan. 5, 2007]

jatar_k

3:51 pm on Jan 5, 2007 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



you missed the loop

this works

<? 
$useragent = $_SERVER['HTTP_USER_AGENT'];
$useragents = array('Firefox','MSIE');
$checkit = '';
$answer = '';
foreach ($useragents as $ua) {
$checkit = stristr($useragent,$ua);
if ($checkit === false) {
$answer = false;
} else {
$answer = true;
break;
}
}
echo '<p>',$useragent;
if ($answer) {
echo '<p>you can come in';
} else {
echo '<p>you are not welcome here';
}
?>

JAB Creations

4:10 pm on Jan 5, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



It took me a few minutes but what you did made sense, thanks! I just don't approach programming with more the a really basic concept and limited set of options.

- John