There are a couple of different ways to include quotation marks within a string in PHP without causing errors. The below code demonstrates them and then I will explain each.
<?php var $mystring="\"hello\"<br />"; echo $mystring; var $mystring=""hello"<br />"; echo $mystring; var $mystring='"hello"<br />'; echo $mystring; ?>
Escaping Special Characters With Backslash
The above code will output 3 lines each containing "hello". The first example uses PHP's escape character to escape the quotation marks inside the string. This tells PHP that you meant the quotation marks literally. You really want them there and didn't mean them for PHP's 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.


Leave a Reply: