PHP is an extremely powerful tool for generating HTML code as well as processing user submitted data.
HTML code and use data is commonly in a string format. This module will cover how to format and
manipulate strings. By using built-in PHP functions and regular expressions a PHP developer can perform
such task as comparing strings, match and replacing substrings, joining or splitting strings.
What is a String?
A string is any sequence of characters, like "Hello world!"
, ‘a’, “123”, “a1b2c3”, $singleVar, etc
. A string
can either be a text string surrounded by either single or double quotes. A variable with a string assigned
to it can also be considered a string, because it stores a string.
When working with strings, it is important to remember all strings must be enclosed in a single or
double quote and the ending quote and must match the beginning quote. If for example you want to the
include a single or double quote in the string, the opposite quotes should be used to declared the string.
For example $myQuote = ‘<p>”
Never on Tuesday
There are two string operators in PHP. The first string operator is the concatenation operator ('.') a
single period, which returns the concatenation of its right and left arguments. The second is the
concatenating assignment operator ('.=') is the period and equal symbol, which appends the string on
the right side to the string on the left side. The string in these examples can be a variable with a string
value or the actual string.
// now $b contains "Hello World!"
// now $a contains "Hello World!"
When working with special characters in PHP strings, special care has to be taken to ensure the string is
interpreted by the PHP engine correctly. If a special character is added to a strings, unusual behavior or
fetal execution errors might occur.
For example, this line of code will have unexpected behavior. The single quote
in the word “it’s” will
prematurely end the strings, whe
n the PHP interpreter match the beginning single quote to the “it’s”
word single quote. Upon execution of this script, a parse error
//Special character caused script to error out