|
Tutorial 9
String Manipulation
Functions demonstrated
- <?strlen($string)>
<?strval($string)>
<?strtok($string,$arg)>
<?strtoupper($string)>
<?strtolower($string)>
<?strstr($string,$arg)>
<?strchr($string,$arg)>
<?strrchr($string,$arg)>
These functions allow you to manipulate strings in various ways. They are similar in
functionality to the corresponding C versions, so you may simply read the C man pages on
your system to get a better idea of how they work.
strlen() returns the length of the string argument.
strval() returns the integer value of the string. The C equivalent of this
function is the atol() function.
strtok() is used to tokenize a string. That is, if you have a string like
"This
is an example string" you could tokenize this string into its individual works by
using the space character as the token. You would use the following script code:
<?
$string = "This is an example string";
$tok = strtok($string," ");
while($tok);
echo "Word=$tok<br>";
$tok = strtok(" ");
endwhile;
>
The output looks like this:
Word=This
Word=is
Word=an
Word=example
Word=string
Note that only the first call to strtok uses the string argument. Every
subsequent call to strtok only needs the token to use as it keeps track of where it is in
the current string. To start over, or to tokenize a new string you simply call strtok with
the string argument again to initialize it.
strtoupper() and strtolower() converts the string argument to all upper
and all lower case characters respectively.
strstr() and strchr() are actually identical functions. They can be used
interchangeably and both are included only for completeness sake. They will return the
portion of the string argument starting at the point where the given sub-string is found.
For example, in our example string from above, the call: <echo
strstr($string,"an ")> would return the string: "an example
string".
strrchr() is identical to strchr except for the fact that it will start
at the end of the string and search backwards for a match.
Another important set of functions to know about when dealing with strings are the
regular expression functions demonstrated in the Regular
Expression Demo.
|