Page 125 - Beginning PHP 5.3
P. 125
Chapter 5: Strings
Once the desired line length has been reached, the justified line is appended to $myTextJustified
(adding a newline character at the end of the line), and the $startOfLine pointer is moved to the
start of the next line (adding 1 to the index to skip over the newline character):
$myTextJustified .= “$justifiedLine\n”;
$startOfLine += $originalLineLength + 1;
Finally, the original and justified blocks of text are displayed in the page:
?>
<h2>Original text:</h2>
<pre><?php echo $myText ?></pre>
<h2>Justified text:</h2>
<pre><?php echo $myTextJustified ?></pre>
</body>
</html>
Translating Characters with strtr()
A fairly common requirement — especially with Web programming — is to be able to replace certain
characters in a string with certain other characters. For example, you might want to make a string “ URL
friendly ” by replacing spaces with + (plus) symbols and apostrophes with - (hyphen) symbols.
This is where strtr() comes in. This function takes three arguments: the string to work on, a string
containing a list of characters to translate, and a string containing the characters to use instead. The
function then returns a translated copy of the string. So you could write a simple script to make a “ URL
friendly ” string as follows:
$myString = “Here’s a little string”;
// Displays “Here-s+a+little+string”
echo strtr( $myString, “ ‘”, “+-” ) . “ < br/ > ”;
strtr() is especially useful if you need to translate a string from one character set to another, because
you can easily map hundreds of characters to their equivalents in the new character set just by passing a
couple of strings.
You can also use strtr() to replace strings with strings, rather than characters with characters. To do
this, pass just two arguments: the string to work on, and an array of key/value pairs, where each key is
the string to search for and each corresponding value is the string to replace it with. More on arrays in the
next chapter.
Dealing with Upper - and Lowercase
Most Western character sets have a concept of upper - and lowercase letters. PHP lets you convert strings
between upper - and lowercase in a variety of ways.
87
9/21/09 8:53:44 AM
c05.indd 87
c05.indd 87 9/21/09 8:53:44 AM