PHP String search functionality

Simple Searching Functionality

PHP provides a number of very powerful search facilities whose functionality varies from the very simple (and correspondingly faster) to the very complex (and correspondingly slower).
The simplest way to search inside a string is to use the strpos() and strstr() families of functions. The former allows you to find the position of a substring (usually called the needle) inside a string (called the haystack). It returns either the numeric position of the needle’s first occurrence within the haystack, or false if a match could not be found. Here’s an example:

$haystack = "abcdefg";
$needle = ’abc’;
if (strpos ($haystack, $needle) !== false) {
echo ’Found’;
}

Note that, because strings are zero-indexed, it is necessary to use the identity operators when calling strpos() to ensure that a return value of zero—which indicates that the needle occurs right at the beginning of the haystack—is not mistaken for a return value of false.

You can also specify an optional third parameter to strpos() to indicate that you want the search to star t from a specific position within the haystack. For example:

$haystack = ’123456123456’;
$needle = ’123’;
echo strpos ($haystack, $needle); // outputs 0
echo strpos ($haystack, $needle, 1); // outputs 6

The strstr() function works similarly to strpos() in that it searches the haystack for a needle. The only real difference is that this function returns the portion of the haystack that starts with the needle instead of the latter’s position:

$haystack = ’123456’;
$needle = ’34’;
echo strstr ($haystack, $needle); // outputs 3456

Both strpos() and strstr() are case sensitive and start looking for the needle from the beginning of the haystack. However, PHP provides variants that work in a case-insensitive way or star t looking for the needle from the end of the haystack. For example:

// Case-insensitive search
echo stripos(’Hello World’, ’hello’); // outputs zero
echo stristr(’Hello My World’, ’my’); // outputs "My World"
// Reverse search

echo strrpos (’123123’, ’123’); // outputs 3

Share this

0 Comment to " PHP String search functionality "

Post a Comment