Specifications
The prototype for strtok() is
string strtok(string input, string separator);
The separator can be either a character or a string of characters, but note that the input string
will be split on each of the characters in the separator string rather than on the whole separator
string (as explode does).
Calling strtok() is not quite as simple as it seems in the prototype.
To get the first token from a string, you call strtok() with the string you want tokenized, and
a separator. To get the subsequent tokens from the string, you just pass a single parameter—the
separator. The function keeps its own internal pointer to its place in the string. If you want to
reset the pointer, you can pass the string into it again.
strtok() is typically used as follows:
$token = strtok($feedback, “ “);
echo $token.”<br>”;
while ($token!=””)
{
$token = strtok(“ “);
echo $token.”<br>”;
};
As usual, it’s a good idea to check that the customer actually typed some feedback in the form,
using, for example, empty(). We have omitted these checks for brevity.
This prints each token from the customer’s feedback on a separate line, and loops until there
are no more tokens. Note that PHP’s strtok() doesn’t work exactly the same as the one in C.
If there are two instances of a separator in a row in your target string (in this example, two
spaces in a row), strtok() returns an empty string. You cannot differentiate this from the
empty string returned when you get to the end of the target string. Also, if one of the tokens is
0, the empty string will be returned. This makes PHP’s strtok() somewhat less useful than
the one in C. You are often better off just using the explode() function.
Using substr()
The substr() function enables you to access a substring between given start and end points of
a string. It’s not appropriate for our example, but can be useful when you need to get at parts
of fixed format strings.
The substr() function has the following prototype:
string substr(string string, int start, int [length] );
This function returns a substring copied from within string.
String Manipulation and Regular Expressions
C
HAPTER 4
4
S
TRING
M
ANIPULATION
103
06 7842 CH04 3/6/01 3:41 PM Page 103