Page 147 - Open Soource Technologies 304.indd
P. 147
Open Source Technologies
Notes strtoupper Returns a string with all characters converted to
uppercase.
substr Extracts a substring from a string.
trim Remove characters (default is remove blanks) from
the beginning and end of a string.
8.7 Accessing String Offsets
Individual characters in a string can be accessed using the $str{offset} notation. You can use it
to both read and write string offsets. When reading characters, this notation should be used
only to access valid indices. When modifying characters, you may access offsets that don’t yet
exist. PHP automatically sets that offset to the said character, and if this results in a gap between
the ending of the original string and the offset of the new character, the gap filled with space
characters (‘ ‘). This example creates and prints the string “Andi” (in an awkward way):
$str = “A”;
$str{2} = “d”;
$str{1} = “n”;
$str = $str . “i”;
print $str;
For many cases, PHP has string manipulation functions which use efficient
algorithms. You should first look at them before you access strings directly
using string offsets. They are usually prefixed with str_. For more complex
needs, the regular expressions functions—most notably the pcre_family of
functions—will come in handy.
In PHP 4, you could use [] (square brackets) to access string offsets. This
support still exists in PHP 5, and you are likely to bump into it often. However,
you should really use the {} notation because it differentiates string offsets
from array offsets and thus, makes your code more readable.
8.8 __toString( ) Method
Consider the following code:
class Person {
function __construct($name)
{
$this->name = $name;
142 LOVELY PROFESSIONAL UNIVERSITY