151

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?

Lightness Races in Orbit
  • 358,771
  • 68
  • 593
  • 989
  • 2
    possible duplicate of [Is it better to use single or double quotes for HTML attributes?](http://stackoverflow.com/questions/242766/is-it-better-to-use-single-or-double-quotes-for-html-attributes) – Brad Werth Sep 29 '14 at 23:22

11 Answers11

154

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.

Community
  • 1
  • 1
Greg Hewgill
  • 828,234
  • 170
  • 1,097
  • 1,237
  • 15
    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 `` to show a inline image it will not appear at all because the content id was ignored. You have to use ` instead. – Earth Engine Feb 12 '13 at 00:51
55

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.

Adam Bellaire
  • 99,441
  • 19
  • 144
  • 160
  • 2
    +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](http://www.w3.org/TR/REC-xml/#NT-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 01 '12 at 12:24
  • 8
    But HTML is based on SGML (it's XHTML which is based on XML) so quoting the XML spec isn't very useful… – Donal Fellows Mar 15 '12 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 '14 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. – user2867288 Jun 21 '16 at 13:18
16

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

That person is wrong.

FlySwat
  • 160,042
  • 69
  • 241
  • 308
  • 32
    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 – Lightness Races in Orbit Jun 10 '11 at 19:29
  • @LightnessRacesinOrbit "What do you mean this browser doesn't support CSS?!" – BadHorsie Jul 30 '15 at 16:01
  • ... or more importantly, "that browser (which does not) is dead meat". :P – ToolmakerSteve Apr 28 '16 at 05:06
  • @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. – user3413723 Apr 24 '18 at 02:57
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.

PhiLho
  • 38,673
  • 6
  • 89
  • 128
4

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.

rink.attendant.6
  • 36,468
  • 57
  • 89
  • 143
inteblio
  • 93
  • 1
  • 6
  • 2
    You can however do: `` – rink.attendant.6 Aug 19 '13 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: `` and vice versa: ``. – Triynko Apr 22 '14 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. ☞ https://en.wikipedia.org/wiki/Quotation_mark#Quotation_marks_in_English – Frank Nocke Sep 23 '15 at 07:15
3

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 5.3

Editor’s Draft, 18 October 2018

[...]

8.1.2.3. Attributes

Single-quoted attribute value syntax

The attribute name, followed by zero or more space characters, followed by a single U+003D EQUALS SIGN character, followed by zero or more space characters, 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 a space character separating the two.

http://w3c.github.io/html/single-page.html#elements-attributes

connexo
  • 41,035
  • 12
  • 60
  • 87
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')};
Rashad
  • 10,519
  • 4
  • 40
  • 67
rchacko
  • 1,591
  • 18
  • 23
1

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

UnkwnTech
  • 79,308
  • 64
  • 178
  • 223
-1

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

Gena Moroz
  • 910
  • 5
  • 7
-2

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

mcandre
  • 19,306
  • 17
  • 77
  • 140
  • I believe you are referring to the [heredoc capability in PHP](http://stackoverflow.com/a/5673478/1497596). – DavidRR Nov 13 '14 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. – AntonChanning Mar 18 '16 at 12:10
-9

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.

Eric Leschinski
  • 123,728
  • 82
  • 382
  • 321
Adam Ness
  • 5,990
  • 4
  • 25
  • 39
  • 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 07 '08 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? – Doug McClean Nov 07 '08 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. – Diodeus - James MacFarlane Nov 07 '08 at 21:50
  • 8
    XHTML requires pages to be well-formed XML, and XML allows either double or single quotes around attributes. – Ned Batchelder Nov 07 '08 at 21:57
  • @SoftwareMonkey Actually, you need `application/xhtml+xml` or `application/xml`. – rink.attendant.6 Aug 19 '13 at 23:43