The strpos function in PHP

 

A more useful thing you'll want to do is to see if one string is inside of another. For example, you can get which browser the user has with this:

$agent = $_SERVER["HTTP_USER_AGENT"];
print $agent;

Try it out and see what gets printed out. You should find that quite along string gets printed.

If you're testing which browser the user has, you can use a string function to search for a short string inside of this very long one. A PHP string function you can use is strpos( ). The syntax for the strpos function is:

strpos( string_to_search, string_to_find, start )

You need to supply at least the first two. The third, start, is optional. Here's a simple example.

$full_name = "bill gates";
$letter_position = strpos( $full_name, "b" );
print $letter_position;

When you run the script, a value of 0 is returned. That's because PHP considers the first character of the string to be at position 0, the second character at position 1, the third at position 2, etc. Since we were searching for the letter "b", and "bill gates" begins with this letter, a value of 0 is returned.

Try changing strpos( ) from this:

$letter_position = strpos($full_name, "b" );

to this:

$letter_position = strpos($full_name, "B" );

What happens when you run the script? Nothing! At least, you don't get a value back. That's because if strpos can't find your characters, it returns a value of false. A value of false in PHP can be tested for by using the triple equals operator. Like this:

$full_name = "bill gates";
$letter_position = strpos($full_name, "B");

if ($letter_position === false) {

print "Character not found " ;

}
else {

print "Character found";

}

The triple equals operator ( === ) not only checks for a value but what type of value it is: integer, string, Boolean, etc. If a string is not found, you need to use this operator, just in case the character you're searching for is at position 0. PHP is a little bit quirky with zeros. It seems them as having a false value as well. But it can be a different kind of false! So use ===.

Here's a script that checks which of two browsers a user has:

$agent = $_SERVER['HTTP_USER_AGENT'];

if ( strpos( strtoupper($agent), 'MSIE') ) {

print "Internet Explorer";

}
else if (strpos(strtoupper($agent), 'FIREFOX')) {

print "Firefox";

}
else {

print $agent;

}

The above script uses two of the string functions that you've met: strpos( ) and strtoupper( ). See if you can figure out what's going on!

 

In the next part, you'll learn how to split a line of text. You'll need to do this when working with, for example, text files.