168

I am a big time user of using double quotes in PHP so that I can interpolate variables rather than concatenating strings. As a result, when I am generating HTML I often use single quotes for setting tag fields. For example:

$html = "<input type='text' name='address' value='$address'>";

Now this is far more readable to me than either

$html = "<input type=\"text\" name=\"address\" value=\"$address\">";

or

$html = '<input type="text" name="address" values="' . $address . '">' ;

From brief searches I have heard people saying that single quotes for HTML fields is not recognized by EVERY browser. Thus I am wondering what browsers would have problems recognizing single quote HTML?

1

11 Answers 11

160

This is similar to When did single quotes in HTML become so popular?. Single quotes around attributes in HTML are and always have been permitted by the specification. I don't think any browsers wouldn't understand them.

1
  • 16
    One thing I need to mention here is that some HTML clients (not necessary browsers) have compatibly issues on single quoting. One strange example is that in Hotmail if you use <img src='cid:xxx' ... /> to show a inline image it will not appear at all because the content id was ignored. You have to use `<img src="cid:xxx" ... /> instead. Feb 12, 2013 at 0:51
59

As noted by PhiLho, although there is a widely spread belief that single quotes are not allowed for attribute values, that belief is wrong.

The XML standard permits both single and double quotes around attribute values.

The XHTML standard doesn't say anything to change this, but a related section which states that attribute values must be quoted uses double quotes in the example, which has probably lead to this confusion. This example is merely pointing out that attribute values in XHTML must meet the minimum standard for attribute values in XML, which means they must be quoted (as opposed to plain HTML which doesn't care), but does not restrict you to either single or double quotes.

Of course, it's always possible that you'll encounter a parser which isn't standards-compliant, but when that happens all bets are off anyway. So it's best to just stick to what the specification says. That's why we have specifications, after all.

4
  • 3
    +1 for the link to the XML standard. I know this is an old thread, but for completeness, people should pay particular attention to the AttValue grammar specification within the standard. If you can read EBNF (very similar to regular expressions) you will see that it allows the use of both single and double quotes to delimit attributes.
    – daiscog
    Feb 1, 2012 at 12:24
  • 10
    But HTML is based on SGML (it's XHTML which is based on XML) so quoting the XML spec isn't very useful… Mar 15, 2012 at 11:06
  • The real confusion is whether single or double quotes in an attribute value always need escaped. It seems that if you use double quotes around the attribute value, then you have to escape double quotes, but not single quotes. If instead you use single quotes around the attribute value, then you'd have to escape single quotes, but not double quotes. And I think that's the whole point of allowing either. If you have a lot of double quotes in your value, you can avoid escaping them by using single quotes around the entire value, and vice versa.
    – Triynko
    Apr 22, 2014 at 17:55
  • The fact of the matter is, if you use an XHTML document mode you will run into Javascript interpreter problems where it tries to force any Javascript-created HTML to use double quotes, breaking attributes with unescaped double quotes inside of them. I ran into this problem in Firefox as well as IE several years ago. Jun 21, 2016 at 13:18
17

I have heard people saying that single quotes for HTML fields is not recognized by EVERY browser

That person is wrong.

4
  • 35
    Not necessarily. I can create a browser in a few minutes that does not recognise single quotes for HTML fields. Of course, there will be a lot more that it doesn't recognise... ;P Jun 10, 2011 at 19:29
  • 1
    @LightnessRacesinOrbit "What do you mean this browser doesn't support CSS?!"
    – BadHorsie
    Jul 30, 2015 at 16:01
  • 1
    ... or more importantly, "that browser (which does not) is dead meat". :P Apr 28, 2016 at 5:06
  • 1
    @LightnessRacesinOrbit - but have you? Seems like anybody motivated enough to make an entire browser is going to put in the extra 5 minutes to make it accept single quotes. Apr 24, 2018 at 2:57
12

As I was looking to find information on this in a much more recent version of the specification and it took me quite some time to find it, here it is:

From

HTML

Living Standard — Last Updated 17 September 2021

[...]

13.1.2.3 Attributes

Single-quoted attribute value syntax

The attribute name, followed by zero or more ASCII whitespace, followed by a single U+003D EQUALS SIGN character, followed by zero or more ASCII whitespace, followed by a single U+0027 APOSTROPHE character ('), followed by the attribute value, which, in addition to the requirements given above for attribute values, must not contain any literal U+0027 APOSTROPHE characters ('), and finally followed by a second single U+0027 APOSTROPHE character (').
In the following example, the type attribute is given with the single-quoted attribute value syntax:

<input type='checkbox'>

If an attribute using the single-quoted attribute syntax is to be followed by another attribute, then there must be ASCII whitespace separating the two.

https://html.spec.whatwg.org/multipage/syntax.html#attributes-2

7

Don't believe everything you see on Internet...
Funnily, I just answered something similar to somebody declaring single quotes are not valid in XHTML...

Mmm, I look above while typing, and see that Adam N propagates the same belief. If he can back up his affirmation, I retract what I wrote... AFAIK, XML is agnostic and accepts both kinds of quote. I even tried and validated without problem an XHTML page with only single quotes.

5

Only problem is data going into TEXT INPUT fields. Consider

<input value='it's gonna break'/>

Same with:

<input value="i say - "this is gonna be trouble" "/>

You can't escape that, you have to use htmlspecialchars.

5
  • 2
    You can however do: <input value='it&apos;s gonna break'/> Aug 19, 2013 at 23:42
  • 4
    I think the reason we have the option to using single or double quotes is to avoid having to escape characters in exactly this scenario. If you have only double quotes in your value, surround it with single quotes to avoid having to escape the double quotes like so: <input value="it's not gonna break"/> and vice versa: <input value='i say - "this is not gonna be trouble"'/>.
    – Triynko
    Apr 22, 2014 at 17:58
  • 1
    @Triynko is right. Besides: For content, consider not using "dumb quotes" in the first place, but “typographic quotes”: Peter’s bar, not Peter's bar. ☞ en.wikipedia.org/wiki/Quotation_mark#Quotation_marks_in_English
    – Frank N
    Sep 23, 2015 at 7:15
  • 1
    This answer is the only sensible advice. Use htmlspecialchars, always. Variable interpolation is great syntactic sugar, but the flip side of the coin is that it easily leads to hard-to-spot XSS vulnerabilities. Jun 4, 2021 at 13:36
  • “You can't escape that…” Well, I’d say HTML entities are a way of escaping.
    – Melebius
    Sep 8, 2021 at 7:08
1

I also tend to use single quotes in HTML and I have never experienced a problem.

1

I used single quotes in HTML pages and embedded JavaScripts into it and its works fine. Tested in IE9, Chrome and Firefox - seems working fine.

<!DOCTYPE html>
<html>
    <head>
        <meta charset='utf-8'>
        <meta http-equiv='X-UA-Compatible' content='IE=edge,chrome=1'>
        <title>Bethanie Inc. data : geographically linked</title>
        <script src='http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js'></script>
        <script src='https://maps.googleapis.com/maps/api/js?v=3.11&sensor=false' type='text/javascript'></script>
        <script type='text/javascript'> 
        // check DOM Ready
        $(document).ready(function() {
            // execute
            (function() {
                /////////////// Addresses ///////////////////
                var locations = new Array();
                var i = 0;
                locations[i++] = 'L,Riversea: Comp Site1 at Riversea,1 Wallace Lane Mosman Park WA 6012'
                locations[i++] = 'L,Wearne: Comp Site2 at Wearne,1 Gibney St Cottesloe WA 6011'
                locations[i++] = 'L,Beachside:Comp Site3 Beachside,629 Two Rocks Rd Yanchep WA 6035'

                /////// Addresses/////////
                var total_locations = i;
                i = 0;
                console.log('About to look up ' + total_locations + ' locations');
                // map options
                var options = {
                    zoom: 10,
                    center: new google.maps.LatLng(-31.982484, 115.789329),//Bethanie  
                    mapTypeId: google.maps.MapTypeId.ROADMAP,
                    mapTypeControl: true
                };
                // init map
                console.log('Initialise map...');
                var map = new google.maps.Map(document.getElementById('map_canvas'), options);
               // use the Google API to translate addresses to GPS coordinates 
               //(See Limits: https://developers.google.com/maps/documentation/geocoding/#Limits)
                var geocoder = new google.maps.Geocoder();
                if (geocoder) {
                    console.log('Got a new instance of Google Geocoder object');
                    // Call function 'createNextMarker' every second
                    var myVar = window.setInterval(function(){createNextMarker()}, 700);
                    function createNextMarker() {
                        if (i < locations.length) 
                       {
                            var customer = locations[i];
                            var parts = customer.split(','); // split line into parts (fields)
                            var type= parts.splice(0,1);    // type from location line (remove)
                            var name = parts.splice(0,1);    // name from location line(remove)
                            var address =parts.join(',');   // combine remaining parts
                            console.log('Looking up ' + name + ' at address ' + address);
                            geocoder.geocode({ 'address': address }, makeCallback(name, type));
                            i++; // next location in list
                            updateProgressBar(i / total_locations);


                        } else 
                       {
                            console.log('Ready looking up ' + i + ' addresses');
                            window.clearInterval(myVar);
                        }
                    }

                    function makeCallback(name,type) 
                   {
                        var geocodeCallBack = function (results, status) {
                            if (status == google.maps.GeocoderStatus.OK) {
                                var longitude = results[0].geometry.location.lng();
                                var latitude = results[0].geometry.location.lat();
                                console.log('Received result: lat:' + latitude + ' long:' + longitude);
                                var marker = new google.maps.Marker({
                                    position: new google.maps.LatLng(latitude, longitude),
                                    map: map,
                                    title: name + ' : ' + '\r\n' + results[0].formatted_address});// this is display in tool tip/ icon color
                                   if (type=='E')  {marker.setIcon('http://maps.google.com/mapfiles/ms/icons/green-dot.png')};
-1

Recently i've experienced a problem with Google Search optimization. If has a single quotes, it doesn't seem to crawl linked pages.

1
  • 1
    Is this just in <a href=''> attributes?
    – ToniWidmo
    Mar 18, 2016 at 12:12
-2

... or just use heredocs. Then you don't need to worry about escaping anything but END.

2
  • I believe you are referring to the heredoc capability in PHP.
    – DavidRR
    Nov 13, 2014 at 14:25
  • Not sure why this answer is downvoted given context of original question. It doesn't directly answer the double verses single quotes issue, but it does address the php escaping issue that lead to OP favouring single quotes in the first place. It could do with an example of usage however.
    – ToniWidmo
    Mar 18, 2016 at 12:10
-10

Single Quotes are fine for HTML, but they don't make valid XHTML, which might be problematic if anybody was using a browser which supported only XHTML, but not HTML. I don't believe any such browsers exist, though there are probably some User-Agents out there that do require strict XHTML.

5
  • 1
    the worse part is people that write HTML pages but mark them as XHTML because it's 'better'. fortunately this fad seems to be going down.
    – Javier
    Nov 7, 2008 at 20:02
  • 4
    I do not believe this statement about XHTML is true. Both " and ' are acceptable in XML, and the W3C validator accepts XHTML documents with single-quoted attributes. Perhaps this may be a confusion with XHTML eliminating unquoted attributes which are legal in HTML? Nov 7, 2008 at 21:10
  • Unless you serve your page as text/xhtml and not text/html browsers will render it as HTML, so HTML rules will apply. Regrdless, one on the w3C principles is NOT TO BREAk THE WEB. Because it works now, it will likely work tomorrow. Nov 7, 2008 at 21:50
  • 8
    XHTML requires pages to be well-formed XML, and XML allows either double or single quotes around attributes. Nov 7, 2008 at 21:57
  • @SoftwareMonkey Actually, you need application/xhtml+xml or application/xml. Aug 19, 2013 at 23:43