Searching strings in PHP

There are several functions in PHP for looking inside strings for substrings. As you saw, the HTTP_USER_AGENT string from the $_SERVER variable contains useful information.

It is possible to search the browser string (which is long and complicated) to see which browser it is and simplify the output:

$browser=$_SERVER["HTTP_USER_AGENT"];
if (strstr($browser, "Safari")) {
    echo "You are using Safari";
}
        

STRSTR is a function built in to PHP which you call as shown here. You will find many more functions as you use PHP but the will all be structured in a similar way:

functioname(stufftosendtofunction)
        

What you send to the function depends what you want it to do. With STRSTR you send the string to be searched and the text you want to find in it. If you send more than one thing to the function you need a comma to separate them.

Try that in a page with different browsers. Change the string to search for and check the results. If you are not sure what to search for you could ECHO the whole user agent string to see what is in it for each browser. Try adding ELSE to show a message if it is not the browser you searched for. Try adding ELSEIF to allow for more than one browser.

You can search any string or string variable for a substring like this so STRSTR will become very useful once you start dealing with lots of information.

submit to reddit Delicious Tweet