Strings

You can't do too much in PHP without learning how to work with Strings. The most important thing to understand is that a string can be enclosed in either double quotes or single quotes. Most of the time, it doesn't matter which one you use. $name="Joe"; is exactly the same as $name='Joe'; However, if the word have a single quote in them such as "I'm OK" then we would use double quotes: echo "I'm OK"; If the words we want to display have double quotes we can use single quotes to enclose them: echo 'He said "yes"';

What if we want to display the words He said, "I'm OK" Any of the following will work:

echo "He said "I'm OK""; //use the code for the quote

echo 'He said "I\'m OK"'; //use the backslash to escape the single quote

echo "He said \"I'm OK\""; //use the backslash to escape the double quote

One important difference however is when a variable is imbedded inside quotes. Consider the code below:

$n=56;
echo 'The value of n is $n.'; //displays The value of n is $n.

echo "The value of n is $n."; //displays The value of n is 56.

Aside from using strings to display information, we also need to be able to manipulate the contents of a string. Fortunately, PHP has lots of built-in functions for string manipulation. Search for PHP strings or look at the manual at http://us2.php.net/strings When looking at the functions in the manual remember that "r" usually means "reverse" and "i" means "insensitive" (not case sensitive.)

Some short examples of the ways we will be using Strings are shown below:

$name=trim($name); //remove blanks from both ends of a string: "  Joe " becomes "Joe"
$state=strtoupper($state); //md becomes MD
if(strlen($socSec)!=9) echo "not a valid Social Security Number";
echo str_repeat("*",20); //displays ********************

Next, we will look at some examples that require several string functions.