Simple Search and Replace Operations

Jun 18, 2009 Author: SEO

Replacing portions of a string with a different substring is another very common task for PHP developers. Simple substitutions are performed using str_replace() (aswell as its case-insensitive variation, str_ireplace()) and substr_replace(). Here’s an example:

echo str_replace("World", "Reader", "Hello World");
echo str_ireplace("world", "Reader", "Hello World");

In both cases, the function takes three parameters: a needle, a replacement string and a haystack. PHP will attempt to look for the needle in the haystack (using either a case-sensitive or case-insensitive search algorithm) and substitute every single instance of the latter with the replacement string. Optionally, you can specify a third parameter, passed by reference, that the function fills, upon return, with the number of substitutions made:

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

If you need to search and replace more than one needle at a time, you can pass the first two arguments to str_replace() in the formof arrays:

echo str_replace
(array("Hello", "World"), array("Bonjour", "Monde"), "HelloWorld");
 echo str_replace 
(array("Hello", "World"), "Bye", "Hello World");

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 need to replace a portion of a needle of which you already know the starting and ending point, you can use substr_replace():

 echo substr_replace("Hello World", "Reader", 6);
echo substr_replace("Canned tomatoes are good", "potatoes", 7, 8);

The third argument is our starting point—the space in the first example; the function replaces the contents of the string from here until the end of the string with the second argument passed to it, thus resulting in the output Hello Reader. You can also pass an optional fourth parameter to define the end of the substring that will be replaced (as shown in the second example, which outputs Canned potatoes are good). Combining substr_replace() with strpos() can prove to be a powerful tool. For example:

$user = "";
$name = substr_replace($user, "", strpos($user, ’@’);
echo "Hello " . $name;

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.

views 3631
  1. Add New Comment