Specifications

You can avoid this problem by using the === operator to test return values:
$result = strpos($test, “H”);
if ($result === false)
echo “Not found”
else
echo “Found at position 0”;
Note that this will only work in PHP 4in earlier versions you can test for false by testing the
return value to see if it is a string (that is, false).
Replacing Substrings: str_replace(), substr_replace()
Find-and-replace functionality can be extremely useful with strings. We have used find and
replace in the past for personalizing documents generated by PHPfor example by replacing
<<name>> with a persons name and <<address>> with their address. You can also use it for
censoring particular terms, such as in a discussion forum application, or even in the Smart
Form application.
Again, you can use string functions or regular expression functions for this purpose.
The most commonly used string function for replacement is
str_replace(). It has the follow-
ing prototype:
string str_replace(string needle, string new_needle, string haystack);
This function will replace all the instances of needle in haystack with new_needle.
For example, because people can use the Smart Form to complain, they might use some color-
ful words. As programmers, we can prevent Bobs various departments from being abused in
that way:
$feedback = str_replace($offcolor, “%!@*”, $feedback);
The function substr_replace() is used to find and replace a particular substring of a string. It
has the following prototype:
string substr_replace(string string, string replacement, int start, int
[length] );
This function will replace part of the string string with the string replacement. Which part is
replaced depends upon the values of the start and optional length parameters.
The start value represents an offset into the string where replacement should begin. If it is 0
or positive, it is an offset from the beginning of the string; if it is negative, it is an offset from
the end of the string. For example, this line of code will replace the last character in $test
with “X”:
$test = substr_replace($test, “X”, -1);
Using PHP
P
ART I
108
06 7842 CH04 3/6/01 3:41 PM Page 108