Dec
02
2008
0

Strings and Patterns: Search

PHP Search

PHP has multiple ways for searching from simple to complex (faster and slower)
needle: what we want to find in a string.
haystack: the string itself.

The first two functions are strpos() and strstr(). The former allows us to search for the needle in the haystack, if it finds a result it returns the position of the needle (what character) if it is not found it returns False.

Their can be up to three perimeters n strpos:
strpos($haystack, $needle, $startposition);
The first one is the main string what we want to search in, the second is what we want to find and the third is the starting point in the string to start searching. In the example bellow we will miss the third perimeter therefore start at character index 0:

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

Remember that in strings the first character has a index of 0, the second of 1. Therefore if the needle is found in the haystack and returns 0 you must treat it as found!

Remember strstr() what just mentioned, it works very similar to strpos() in that is searches for a needle in a haystack. Except that where STRPOS returns a character value or false, strstr returns the found result and any characters after the result is found, as shown in the bellow example:

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

strstr() is slower than strpos() and strstr() can not be given a start point to start searching for the perimeter.

PHP Comparing

Comparasons (as you know) is the most common operation performed on strings. One problem we have is that when converting strings to compare them ther may be some problems, concider the following:

$string = ’123aa’;
if ($string == 123) {
// The string equals 123
}

You and I would expect ths to return False, but since PHP first transparently converts the contents of
$string to the integer 123, thus making the comparison true. The best way to compare the above is to use the type comparison like such ===, this compares the value and the data type. In addition to comparison operators, you can also use the specialized functionsstrcmp() and strcasecmp() to match strings. These are identical, with the exception that the former is case-sensitive, while the latter is not. In both cases, a result of zero indicates that the two strings passed to the function are equal:

$str = "Hello World";
if (strcmp($str, "hello world") === 0) {
// We won’t get here, because of case sensitivity
}
if (strcasecmp($str, "hello world") === 0) {
// We will get here, because strcasecmp()
// is case-insensitive
}
Written by Adam in: 07. Strings and Patterns | Tags: , ,

WordPress Powered, Theme by TheBuckmaker.com | Add to Technorati Favorites. | RSS and Comments RSS