Specifications
We will look at examples using this test string:
$test = “Your customer service is excellent”;
If you call it with a positive number for start (only), you will get the string from the start
position to the end of the string. For example,
substr($test, 1);
returns “our customer service is excellent”. Note that the string position starts from 0,
as with arrays.
If you call substr() with a negative start (only), you will get the string from the end of the
string minus start characters to the end of the string. For example,
substr($test, -9);
returns “excellent”.
The length parameter can be used to specify either a number of characters to return (if it is
positive), or the end character of the return sequence (if it is negative). For example,
substr($test, 0, 4);
returns the first four characters of the string, namely, “Your”. The following code:
echo substr($test, 4, -13);
returns the characters between the fourth character and the thirteenth to last character, that is,
“customer service”.
Comparing Strings
So far we’ve just used == to compare two strings for equality. We can do some slightly more
sophisticated comparisons using PHP. We’ve divided these into two categories: partial matches
and others. We’ll deal with the others first, and then get into partial matching, which we will
require to further develop the Smart Form example.
String Ordering: strcmp(),strcasecmp(), and strnatcmp()
These functions can be used to order strings. This is useful when sorting data.
The prototype for strcmp() is
int strcmp(string str1, string str2);
The function expects to receive two strings, which it will compare. If they are equal, it will
return 0. If str1 comes after (or is greater than) str2 in lexicographic order, strcmp() will
Using PHP
P
ART I
104
06 7842 CH04 3/6/01 3:41 PM Page 104