Page 104 - Open Soource Technologies 304.indd
P. 104
Web Technologies-I
Notes Objectives
After studying this unit, you will be able to:
• Understand how to quote string constants
• Discuss about the printing strings
• Understand how to access the character
• Explain cleaning the strings
• Discuss the encoding and escaping
• Explain comparing strings
• Discuss how to manipulating and searching strings
• Discuss the regular expressions
Introduction
The string in PHP is implemented as an array of bytes and an integer indicating the length of the
buffer. It has no information about how those bytes translate to characters, leaving that task to the
programmer. There are no limitations on the values the string can be composed of; in particular,
bytes with value 0 (“NUL bytes”) are allowed anywhere in the string (however, a few functions,
said in this manual not to be “binary safe”, may hand off the strings to libraries that ignore data
after a NUL byte).
5.1 Quoting String Constants
There are three ways to write a literal string in your program: using single quotes, double quotes,
and the here document (heredoc) format derived from the UNIX shell. These methods differ in
whether they recognize special escape sequences that let you encode other characters or interpolate
variables.
The general rule is to use the least powerful quoting mechanism necessary. In practice, this
means that you should use single-quoted strings unless you need to include escape sequences or
interpolate variables, in which case you should use double-quoted strings. If you want a string
that spans many lines, use a heredoc.
5.1.1 Variable Interpolation
When you define a string literal using double quotes or a heredoc, the string is subject to variable
interpolation. Interpolation is the process of replacing variable names in the string with the values
of those variables. There are two ways to interpolate variables into strings—the simple way and
the complex way.
The simple way is to just put the variable name in a double-quoted string or heredoc:
$who = ‘Kilroy’; $where = ‘here’; echo “$who was $where”; Kilroy was here
The complex way is to surround the variable being interpolated with curly braces. This method
can be used either to disambiguate or to interpolate array lookups. The classic use of curly braces
is to separate the variable name from surrounding text:
$n = 20; echo “You are the {$n}th person”; You are the 20th person
Without the curly brackets, PHP would try to print the value of the $nth variable.
98 LOVELY PROFESSIONAL UNIVERSITY