Hosting Fanatic

Go Daddy $1.99 Domains 468x60
Adam Sullivan - Friday 13th of June 2008 03:35:36 AM

PHP Quotation Marks in String - PHP Quick Reference

PHP Quotation Marks in a String

There are a couple of different ways to include quotation marks within a string in PHP. The below code demonstrates them and then I will explain each.

<?php
var $mystring="\"hello\"<br />";
echo
$mystring;

var
$mystring="&quot;hello&quot;<br />";
echo
$mystring;

var
$mystring='"hello"<br />';
echo
$mystring;
?>

Escaping Special Characters With Backslash

The above code will output 3 lines each containg "hello". The first example uses PHPs escape character to escape the quotation marks inside the string. This tells PHP that you ment the quotation marks literally. You really want them there and didn't mean them for PHPs benefit.

The backslash can be used to escape many different types of special characters. This is the most common way of putting quotes in quotes within PHP.

Quotes as HTML Entities

HTML has special characters that can confuse it too. Examples would be > and <. Using these characters within the content on your site can cause HTML to think they are pieces of HTML tags. HTML has special character codes you can use to display these characters without causing confusion.

The second example uses these character codes to display quotes without confusing either PHP or HTML. For more information on HTML Entities visit HTML Entities - W3 Schools

Using Single Quotes

When working with strings in PHP remember that PHP will treat a string differently depending on whether it's in single (apostrophe) or double quotation marks. If there is no reason for PHP to look for variables in a string use single quotes. This way PHP will know not to look and you will save PHP some time.

If a string is in double quotes then PHP will look for variables like $myvariable within the quotes and replace them with their corresponding values.

The third example uses single quotes because the string doesn't need to be parsed by PHP. We then include our double quotes inside and PHP takes them literally because the string is already encased in single quotation marks. PHP doesn't get confused this way.

Blink   Del.icio.us   Digg   Furl   Google   Simpy   Spurl   Y! MyWeb