Working With Strings in PHP
By Stephen Bucaro
Computer programs usually work with some form of data. One of the most common forms
of data used in PHP is a text character or an array of text characters. An array
of text characters is called a string variable, or just a string.
To define a string variable, you place the characters within quotes and use the equals
sign (=) to assign the string value to a properly named variable. You can place the
string characters within single quotes or double quotes, but the you must use the same
type of quotation mark at the end of the string that you used at the beginning of the string.
A string character can be a letter, digit, space, or punctuation mark. Shown below
are examples of properly declared string variables:
<?php
$title = "PHP and MySQL for Dynamic Web Sites";
$ISBN = '0-321-78407-3';
?>
To display the value of a string on a webpage you can use the print function
as shown below:
<?php
$author = "Larry Ullman";
print $author;
?>
You can also use the print function to print a string directly, but this type
of string would actually be a string constant because you could not change its
value programmatically at run time. An example of this is shown below:
<?php
print "bucarotechelp.com";
?>
Using Escape Characters
If you want to use quotation marks within a string, you can use the opposite type
of quote than you used to define the sting. For example if you want to use double
quotes within a sting you must use single quotes to define the string. An example
of this is shown below:
<?php
$define = 'A "string" is an array of characters.';
?>
If you must use the same type of quotation mark within a string that you used
to define the string, then you must use the quotation mark escape character.
An example of this is shown below:
<?php
$statement = "Jerry said, \"I didn't eat the last piece of pizza.\"";
?>
Below are some other useful escape characters:
Escape | Use For |
\n | new line |
\t | tab |
\\ | backslash |
\$ | dollar sign |
Concatenating Strings
To concatenate means to connect in series. When you concatenate stings you
connect two or more stings together. In PHP a period (.) is the concatenation operator.
An example of concatenating strings is shown below.
<?php
$first = "Jim";
$last = " Shoe";
$name = $first . $last;
print $name;
?>
The first line of code defines the variable $first and assigns it the string "Jim".
The second line defines the variable $last and assigns it the string " Shoe".
The third line uses the concatenation operator to combine $first and $last and assigns
the result to the variable $name. The last line uses the print function to
print the value of $name, which would be "Jim Shoe".
|