note 664 modified in String functions by ronabop
| From: | ronabop@php.net | Date: | Fri, 11 Aug 2000 17:04:57 +0000 |
| Subject: | note 664 modified in String functions by ronabop | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-1311@lists.php.net to get a copy of this message | ||
One important thing to be aware of when dealing with strings is the meaning of special character
sequences and the difference between using _single quotes_ and _double quotes_.
A "normal" string assignment looks like this:
$str = "Some string...";
As you probably already noticed elsewhere in this manual you could also use
$name = "Joe";
$str = "Hello $name"; // results in "Hello Joe"
Now it gets a bit tricky:
If your string contains certain special character sequences beginning with a backslash (often
referred to as "escape sequences" or "control codes" or similar), PHP will
evaluate them and act accordingly. The most useful control codes are \t and \n. \t results in a
"TAB", while \n inserts a newline.
So...
echo "Hello $name\nWelcome to\twonderland"
Will give something like
Hello Joe
Welcome to( t a b ) wonderland
(Naturally, it won't show up this way in your browser unless its inside a <PRE>
</PRE> block.)
Of course, if you already know any other language like C or JAVA, all this won't tell you
anything new.
There is a pitfall however, that when e.g. you want to store Windows paths in a string and/or output
it the behavior above may bite you.
Example:
$win_path = "c:\test\mytext.txt";<br>
echo $win_path;
This will look like
c:( t a b ) est\mytext.txt
in the HTML code PHP generates, because it really means "c:(TAB)\mytext.txt"!
Since this is probably not what you intended, you should use single quotes in this case:
$win_path = 'c:\test\mytext.txt';
The single quotes will ensure that PHP treats this string verbatim, so the \t in this example
wouldn't result in a TAB. Be aware that this also prevents PHP from expanding any variables, so
echo 'Hello $name'; // this outputs Hello $name !
doesn't work as you might expect.
Another means of preventing special character sequences from being evaluated is "escaping"
them.
(BTW: This concept is also found in many other languages.) What does this mean?
In the above example we could've also written:
$win_path = "c:\\test\mytext.txt";
echo $win_path; // outputs c:\test\mytext.txt
This effectively tells PHP not to interpret the \t as a TAB. Accordingly, the same goes for \\n etc.
Now you may ask "Argh, do I have to really take care of this myself - Why can't PHP do it
for me?"
The answer is yes, it can: Just use the addslashes() function. If you want to know more about it,
read the appropriate section.
http://www.php.net/manual/string-functions.php