25.09.2014 Views

ZEND PHP 5 Certification STUDY GUIDE

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

82 ” Strings And Patterns<br />

echo str_replace("World", "Reader", "Hello World");<br />

echo str_ireplace("world", "Reader", "Hello World");<br />

In both cases, the function takes three parameters: a needle, a replacement string<br />

and a haystack. <strong>PHP</strong> will attempt to look for the needle in the haystack (using either<br />

a case-sensitive or case-insensitive search algorithm) and substitute every single instance<br />

of the latter with the replacement string. Optionally, you can specify a third<br />

parameter, passed by reference, that the function fills, upon return, with the number<br />

of substitutions made:<br />

$a = 0; // Initialize<br />

str_replace (’a’, ’b’, ’a1a1a1’, $a);<br />

echo $a; // outputs 3<br />

If you need to search and replace more than one needle at a time, you can pass the<br />

first two arguments to str_replace() in the form of arrays:<br />

echo str_replace(array("Hello", "World"), array("Bonjour", "Monde"), "Hello<br />

World");<br />

echo str_replace(array("Hello", "World"), "Bye", "Hello World");<br />

In the first example, the replacements are made based on array indexes—the first<br />

element of the search array is replaced by the first element of the replacement array,<br />

and the output is “Bonjour Monde”. In the second example, only the needle<br />

argument is an array; in this case, both search terms are replaced by the same string<br />

resulting in “Bye Bye”.<br />

If you need to replace a portion of a needle of which you already know the starting<br />

and ending point, you can use substr_replace():<br />

Licensed to 482634 - Amber Barrow (itsadmin@deakin.edu.au)<br />

echo substr_replace("Hello World", "Reader", 6);<br />

echo substr_replace("Canned tomatoes are good", "potatoes", 7, 8);

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!