Dec
02
2008
0

Strings and Patterns: Replacing

Sometimes you need to replace a section of a string wth a different values the functions that do this are:
str_replace();
str_ireplace(); case-insensitive
sbstr_replace();

echo str_replace("World", "Reader", "Hello World"); //Outputs Hello Reader
echo str_ireplace("world", "Reader", "Hello World"); //Outputs Hello Reader (notice its in wrong case)

The functions as you see take three parameters a needle, the replacement string and the haystack. PHP will find the needle in the haystack and substitute every instance with the replacement. Their can be an additional parimiter added to the functions this is a counter of how many replacements their where:

$a = 0; // Initialize
str_replace (’a’, ’b’, ’a1a1a1’, $a);
echo $a; // outputs 3

You can also use arrays with these functions for mass replace like so:

In the first example, the replacements are made based on array indexes—the first element of the search array is replaced by the first element of the replacement array, and the output is “Bonjour Monde”. In the second example, only the needle argument is an array; in this case, both search terms are replaced by the same string resulting in “Bye Bye”.

If you do not know the needle, but do know the character location of what you want to replace you can use substr_replace(); unlike the previous functions the first perimeter is the Haystack, the second is the replacement, the third is the start position and the optional forth is the amount of characters. Here is the function in an examples:

echo substr_replace("Hello World", "Reader", 6); //Outputs Hello Reader, as the 6th character is before the "W" the start of the word World
echo substr_replace("Canned tomatoes are good", "potatoes", 7, 8); //output Canned potatoes are good

As you can see in the first example no fourth perimeter was used, so it replaced the whole end of the string. The second example started at character 7 (the space before tomatoes) and the fourth perimeter was 8 the total length of the word potatoes.

Combining substr_replace() with strpos() can prove to be a powerful tool.

$user = "davey@php.net";
$name = substr_replace($user, "", strpos($user,@);
echo "Hello " . $name;

This will output “Hello davey”
By using strpos() to locate the first occurrence of the @ symbol, we can replace the rest of the e-mail address with an empty string, leaving us with just the username, which we output in greeting.

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