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.
No Comments »
RSS feed for comments on this post. TrackBack URL











