Page 149 - Open Soource Technologies 304.indd
P. 149
Open Source Technologies
Notes
magine we are working at a school district and need to create a webpage for the students’
parents. The webpage has an introduction string that we need to customize depending
Ion if the student is male or female. With str_replace this is mighty easy.
PHP Code:
//string that needs to be customized
$rawstring = “Welcome Birmingham parents. Your replaceme is a pleasure to have!”;
//male string
$malestr = str_replace(“replaceme”, “son”, $rawstring);
//female string
$femalestr = str_replace(“replaceme”, “daughter”, $rawstring);
echo “Son: “. $malestr . “<br />”;
echo “Daughter: “. $femalestr;
Output:
Son: Welcome Birmingham parents. Your son is a pleasure to have!
Daughter: Welcome Birmingham parents. Your daughter is a pleasure to have!
In the last example we only needed to replace one word replacement in our string, but what
if we wanted to replace many words? We could just use the function multiple times to get
the job done, or we could create an array of placeholders and a second array of replace values to
get it all done in one function call.
The key thing to understand with this technique is that you are creating two arrays that will
be used to swap values. The first item in placeholders will be replaced by the first item in
the replace values, the second item of placeholders replaced with the second in replace values and
so on and so forth.
Let’s extend our simple example to be a complete form letter addressed to a student’s parents.
PHP Code:
//string that needs to be customized
$rawstring = “Welcome Birmingham parent! <br />
Your offspring is a pleasure to have!
We believe pronoun is learning a lot.<br />
The faculty simple adores pronoun2 and you can often hear
them say \”Attah sex!\“ ”<br />”;
//placeholders array
Contd...
144 LOVELY PROFESSIONAL UNIVERSITY