Skip to Main Content
PHP in a Nutshell
book

PHP in a Nutshell

by Paul Hudson
October 2005
Intermediate to advanced content levelIntermediate to advanced
372 pages
11h 35m
English
O'Reilly Media, Inc.
Content preview from PHP in a Nutshell

Name

strpos()

Synopsis

    int strpos ( string haystack, mixed needle [, int offset] )

The strpos() function, and its case-insensitive sibling, stripos(), returns the index of the beginning of a substring's first occurrence within a string. This is easiest to understand in code:

    $string = "This is a strpos() test";
    print strpos($string, "s") . "\n";

That will return 3, because the first lowercase S character in "This is a strpos() test" is at index 3. Remember that PHP considers the first letter of a string to be index 0, which means that the S strpos() found is actually the fourth character.

You can specify whole words in parameter two, which will make strpos() return the first position of that word within the string. For example, strpos($string, "test") would return 19—the index of the first letter in the matched word.

You should be aware that if the substring sent in parameter two is not found in parameter one, strpos() will return false (as opposed to -1). This is very important, as shown in this script:

    $string = "This is a strpos() test";
    $pos = strpos($string, "This");
    if ($pos =  = false) {
            print "Not found\n";
    } else {
            print "Found!\n";
    }

That will output "Not found", despite "This" quite clearly being in $string. This time, the problem is that "This" is the first thing in $string, which means that strpos() will return 0. However, PHP considers 0 to be the same value as false, which means that our if statement cannot tell the difference between "Substring not found" and "Substring ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

PHP Cookbook

PHP Cookbook

Eric A. Mann
Programming PHP

Programming PHP

Rasmus Lerdorf, Kevin Tatroe
Learning PHP

Learning PHP

David Sklar

Publisher Resources

ISBN: 0596100671Errata Page