CSS itself will not give an error, however CSS which has an error in its syntax will not render correctly. The browser may not be able to understand what is meant at a given point, and therefore not be able to format the page correctly.
There’s also a difference in CSS being syntactically correct, where everything is properly enclosed and lines terminated, and it being standards compliant according to the W3C specification.
EDIT : (example for syntax correctness and standards compliance)
The following is an example of syntactically correct CSS, which won’t fail validation on the W3C CSS Validator:
p.my-class {
color : red;
-moz-border-radius : 3px;
}
Whilst this is technically valid CSS, according to the vendor specific extensions section of the CSS 2.1 syntax, they should be avoided. It’s the initial dash or underscore which lets them be valid.
answered Oct 16, 2015 at 12:14
gabe3886gabe3886
4,2153 gold badges26 silver badges31 bronze badges
2
I think the question is too broad and not specific.
This is how I would have answered the question.
Is CSS giving error ?
Depends on the place you are looking at.
In a IDE? sure it will show you validation errors.
In browser? Most browsers tend to ignore CSS validation errors and continue with rest of the rules.Again as @Kishan Choudhary mentioned in another answer «CSS» refers just the styling language and languages cannot prompt you errors by themselves.
Alt. Question: How can we validate/debug/find errors in a CSS?
Can we say that CSS does not give any error?
Again it depends on the place you are looking at.
In development environment? Yes almost all web IDEs will help you to find your CSS mistakes.
In Client browser? Not so much,You can open browser console/developer tool if available and there might be logs errors, for example invalid or unreachable URLs of images you have used in CSS. Again is it a CSS syntax or validation error?nope
Is there an interpreter working behind CSS which blocks execution of
the program?
Yes every browser has an inbuilt CSS interpreter/parser following W3C standards and does it like to block execution?No,normal behavior of all most all browsers is to that ignore (not to block interpreting and applying remaining valid style rules) CSS validation errors and continue with rest of the rules.
Update: W3 Guidelines Handling CSS Parsing Errors
Cascading Style Sheets Level 2 Revision 1 (CSS 2.1) Specification
4.2 Rules for handling parsing errors
In some cases, user agents must ignore part of an illegal style sheet.
This specification defines ignore to mean that the user agent parses
the illegal part (in order to find its beginning and end), but
otherwise acts as if it had not been there. CSS 2.1 reserves for
future updates of CSS all property:value combinations and @-keywords
that do not contain an identifier beginning with dash or underscore.
Implementations must ignore such combinations (other than those
introduced by future updates of CSS).To ensure that new properties and new values for existing properties
can be added in the future.
CSS Syntax Module Level 3
2.2. Error Handling
When errors occur in CSS, the parser attempts to recover gracefully,
throwing away only the minimum amount of content before returning to
parsing as normal. This is because errors aren’t always mistakes — new
syntax looks like an error to an old parser, and it’s useful to be
able to add new syntax to the language without worrying about
stylesheets that include it being completely broken in older UAs.
answered Oct 27, 2015 at 3:30
DeshanDeshan
2,10225 silver badges29 bronze badges
Generally errors in the CSS doesn’t cause any error messages in the browser. Any incorrect code is simply ignored (or in some cases accepted by assuming a missing part, e.g. a length unit).
The CSS parser tries to recover after each incorrect code, so usually it will only affect the style or the rule where the error is, the parser won’t just stop parsing the rest of the CSS code.
Some browsers will add warnings to the error console for errors in the CSS, so developers can open the console to see if there is any errors.
answered Oct 16, 2015 at 12:19
GuffaGuffa
679k108 gold badges728 silver badges999 bronze badges
2
Is CSS giving error ?
Yes, any rule which cannot be understood by CSS parser will lead to an error. In general any data which cannot be handled by a system/program will lead to an error. But how the system finally handles that error is your question and it can be
- Ignore the error and continue to process.
- Halt the process.
The CSS parser will not halt on an error. It just puts an error log to the console if it finds any invalid css property which cannot be parsed/ mentioned in specs and ignores(1) all the css-rule data till it finds next ;
.
As w3c.org doc says
A UA must skip a declaration with an invalid property name or an
invalid value.
Here UA(User Agent) means browser in our case. So the invalid css keys/values has to be skipped and the browser vendor may choose to show error in devtools/firebug to help developers to fix it. Also it is browser vendor dependent to put error logs or not.
answered Oct 26, 2015 at 15:46
rajuGTrajuGT
6,1542 gold badges26 silver badges44 bronze badges
Some browsers will report CSS errors in the console. Firefox comes to mind.
<style> foo { bar: baz; } </style>
results in the error:
Unknown property ‘bar’. Declaration dropped. css-error.html:2:11
However, this will not «block execution of the program».
To my knowledge, no similar feature exists in Chrome.
answered Oct 26, 2015 at 3:46
In the CSS there is no errors but you can face some errors in the browser’s console,
That could be the browser giving error but not CSS throwing error.
answered Oct 26, 2015 at 4:57
Anand JainAnand Jain
2,3456 gold badges38 silver badges66 bronze badges
I think the «Is CSS giving error?» statement is ambiguous, but let’s first take a look at this link (CSS 2.1 Specification), jump to 4.2 Rules for handling parsing errors
The specification explicitly specifies how parsing errors should be ignored, in fact, it says:
This specification
defines ignore to mean that the user agent parses the illegal part (in order to find
its beginning and end), but otherwise acts as if it had not been there
In fact, in same cases it even specifies how to turn an invalid piece of css into a valid one:
User agents must close all open constructs (for example: blocks, parentheses,
brackets, rules, strings, and comments) at the end of the stylesheet. For
example:
@media screen {
p:before { content: ’Hello
would be treated the same as:
@media screen {
p:before { content: ’Hello’; }
}
So looking from this perspective, CSS never «gives» errors, because any errors will be effectively parsed and fixed or ignored, but will never stop execution of the rules nor the parser.
However, if you have one developer talking to another in front of an IDE, I think it would be fair enough to ask «Is the CSS giving errors» referring to the IDE’s messages and in fact, if we look at a CSS parser project we can clearly see in the documentation that the parser can give error messages, it’s just browsers that were directly instructed to ignore errors.
answered Dec 5, 2015 at 1:35
Eduardo WadaEduardo Wada
2,56618 silver badges31 bronze badges
CSS is not a real programming language but a domain-specific language (https://en.wikipedia.org/wiki/Domain-specific_language).
In contrast to scripting languages like JavaScript or PHP (which are Turing-complete programming languages) as well as real programming languages like Java or C CSS will not «give errors» as CSS-code is not real program source code.
However as any domain specific language CSS has a syntax and is read by an interpreter (very similar to a declarative Turing-complete programming language).
If the syntax is not correct (test here: https://jigsaw.w3.org/css-validator/#validate_by_input) the CSS is invalid. It depends on the interpreter used how to deal with invalid CSS parts, interpreters in common Web browsers will not halt on CSS syntax errors.
This question therefore can not be explicitly answered:
- CSS can be invalid (syntax)
- CSS can have «syntax errors»
- CSS will not «give» errors and errors are usually just ignored by common interpreters
answered Oct 27, 2015 at 3:18
BlackbamBlackbam
16.4k24 gold badges94 silver badges146 bronze badges
@om. yes it can block your program but in very rear cases. For example if you relay on the width of the element and if you set a display:none to the element and did not make a case to return undefined your application will stuck because your parameter will not have a value.
So it can prevent the execution with interference with other languages.
However how other say in their answers, only css can trow a error for missing file or something like this, but it will not stop the execution of the application.
But i have seen a problem when css property can make a jquery method not working properly and for this the jquery throw error and stop the execution of the application.
answered Dec 4, 2015 at 9:10
2
css can block program in such a way, if you have button and some css properties are not allowing it to display well on your page, in that case we can say it is blocking, otherwise it is not blocker for execution.
even errors don’t block the execution, it just misplace or display the things improperly.
answered Oct 26, 2015 at 9:56
The answers depends on how you define Error.
If Error means happening of something unexpected, then CSS surely gives errors, cause, it wont work if you have something wrong in the syntax.
If Error means throwing something to browser or console, CSS doesn’t do so.
If Error means something which breaks the workflow and stops the execution of the next part of codes, CSS doesn’t.
If you consider point 2 and 3, you may consider CSS errors like warnings in PHP or other programming languages. Only difference is that, in PHP we have option to turn them on to throw something in the browser. CSS doesn’t have any such option till now.
answered Dec 10, 2015 at 10:34
Tᴀʀᴇǫ MᴀʜᴍᴏᴏᴅTᴀʀᴇǫ Mᴀʜᴍᴏᴏᴅ
4,0711 gold badge19 silver badges53 bronze badges
CSS rendering is a process of the browser (or similar) and is intended to not «throw an error» (exception, etc). …In theory.
(bugs in libs/dependencies could cause true errors such as a certain combination of characters freaking out the greater OS. These bugs are well documented on all operating systems and beyond but operate on the fringe of this inquiry)
I have read many times, from many sources, that each browser desires a compliant CSS feature and does their best to «absorb» bad or mistake riddled syntax recovering as promptly as possible. Having a CSS interpreter hang (error) is totally possible, but I always think of the final implementation of CSS parsing as a flavor of a major anti-pattern in Python:
# bad code, just some theory, my Python code "always works"
try:
# code
except:
pass
where any and all errors are swallowed.
As others have stated, «Is CSS giving error?» is a bad or possibly trick question. CSS is syntax or language.
So here’s the real deal: Language gives no errors and has no capacity for error. Only the interpretation of the language may errors be provided (as a product of evaluation). Only the evaluation has the capacity to find error.
If the term «parser» was added to the question then YES, the CSS parser is giving error. But as the phrase stands in your (un-edited) post, I would answer with some linguistic whoop-a$$ and a little CS-101: No, here’s why…
Just my $0.02 from a Programmer + Linguist.
answered Oct 27, 2015 at 1:15
MarcMarc
1,91316 silver badges24 bronze badges
2
«Is CSS giving error ?» — No
CSS itself don’t gives error. It will just ignore that attribute if it is incorrect. If there is syntax error then it will also ignore the same and if any other selector get effected due to syntax error (like missing of ‘}’) that also will be ignored.
There are various IDE (like visual studio) highlight your errors.
As gabe3886 told you can also validate your syntax using W3C CSS Validator
answered Oct 27, 2015 at 2:40
NO, CSS never gives an error. You will not be able to see any error in console or anywhere caused by CSS.
As CSS is just styling language and if something doesn’t get styled as expected it will not be reported as error.
To note that we have buggy CSS code we will have to look at the page and some elements on the page will be get rendered as expected. There are some tricks to Debug your CSS code.
answered Oct 27, 2015 at 3:00
html is a markup language, it does not contains errors so as css
if there is something gone wrong, it tries to show what is right upto the mark
css has no errors, but warnings as we can see in console that specific properties are invalid
like using -webkit-
while viewing in safari
or mozilla
answered Dec 9, 2015 at 16:44
No, «CSS does not give error,» but I think that the interviewer may have been mis-stating the question.
If the interviewer was not mis-stating the question, then we can definitively say that no, CSS does not give errors. There is no evaluator or compiler in the CSS spec that scans your cascade looking for errors. It could even be argued that browsers do not have error handling for CSS, as all commonly used browsers actually discard erroneously written declarations and then search for the nearest semi-colon, and then go back to the reading cascade.
Tab Atkins Jr has a good explanation of how browsers handle errors in CSS and why they handle them that way.
If the browser is in trying to parse a declaration and it encounters something it doesn’t understand, it throws away the declaration, then seeks forward until it finds a semicolon that’s not inside of a {}, [], or () block.
So if the interviewer was trying to play gotcha with this question, I think you could confidently answer that no, CSS is not giving error. But, there’s a decent chance that the interviewer may not really understand CSS or how browsers interpret CSS and wants you to find the errors in a block of CSS. Never be shy to ask an interviewer what they might mean when they ask a question, or if it doesn’t sound clear to you.
answered Dec 10, 2015 at 3:07
Is CSS giving error?
Does CSS work on its own with it’s own separated «compiler»?
Sure, NOT, as for CSS the browser is the component of the execution process that gives errors while CSS on its own cant.
Example
#foo{
Bar: 50%;
Nonsense: 100%;
color: red
}
In this case the browser will ignore the Bar ans Nonsense proprieties and jump to color propriety. And you will have no Exception or error thrown, unlike JS (just for comparison).
So the obvious answer is No!
answered Oct 26, 2015 at 17:08
El DonEl Don
8927 silver badges14 bronze badges
Yeah, exactly right sometime CSS can also giving Error, But it is not through an error, instead of it stop the styling after where the Syntax has an error.
CSS
.myClass {
color : red
background-color : green;
}
This code will giving error, while the code will not execute in this case.
answered Dec 9, 2015 at 4:25
Kamal KumarKamal Kumar
2003 silver badges11 bronze badges
In the conclusion I can say in @Kishan Choudhary’s words «Is CSS giving error ?» — No
but there may be parsing and browser giving errors.
These points are help me to got conclusion.
- CSS itself will not give an error. (@gabe3886)
- Generally errors in the CSS doesn’t cause any error messages in the browser. Any incorrect code is simply ignored
The specification explicitly specifies how parsing errors should be ignored. (@Guffa) - The CSS parser will not halt on an error. It just puts an error log to the console if it finds any invalid css property which cannot be parsed/ mentioned in specs and ignores(1) all the css-rule data till it finds next ;. (@rajuGT)
- The invalid css keys/values has to be skipped and the browser vendor may choose to show error in devtools/firebug to help developers to fix it. (@rajuGT)
- «Is CSS giving error ?» — No | CSS itself don’t gives error. It will just ignore that attribute if it is incorrect. (@Kishan Choudhary)
- However as any domain specific language CSS has a syntax and is read by an interpreter (very similar to a declarative Turing-complete programming language). (@Blackbam)
- Yes it can block your program but in very rear cases. (@George Plamenov Georgiev)
- CSS never «gives» errors, because any errors will be effectively parsed and fixed or ignored, but will never stop execution of the rules nor the parser. (@Eduardo Wada)
- Yeah, exactly right sometime CSS can also giving Error, But it is not through an error, instead of it stop the styling after where the Syntax has an error. (@Kamal Kumar)
- Most browsers tend to ignore CSS validation errors and continue with rest of the rules. (@DeshanR)
- In console, If a background image path is incorrect it will show an error like: Failed to load resource: net::ERR_FILE_NOT_FOUND (@om)
- @om, That is not CSS throwing error. That is the browser giving error because it could not load the resource. (@Farzad YZ)
Thanks guys.
answered Dec 10, 2015 at 7:20
om_jaipurom_jaipur
2,1564 gold badges30 silver badges54 bronze badges
@jasonlyu123 hi! Thanks for reply.
This is my rollup.config.js
for Sapper:
import resolve from "@rollup/plugin-node-resolve"; import replace from "@rollup/plugin-replace"; import commonjs from "@rollup/plugin-commonjs"; import svelte from "rollup-plugin-svelte"; import babel from "@rollup/plugin-babel"; import { terser } from "rollup-plugin-terser"; // Import svelte-preprocess import sveltePreprocess from "svelte-preprocess"; // Import PostCSS plugins import autoprefixer from "autoprefixer"; import pimport from "postcss-import"; import minmax from "postcss-media-minmax"; import csso from "postcss-csso"; import config from "sapper/config/rollup.js"; import pkg from "./package.json"; const mode = process.env.NODE_ENV; const dev = mode === "development"; const legacy = !!process.env.SAPPER_LEGACY_BUILD; const onwarn = (warning, onwarn) => (warning.code === "CIRCULAR_DEPENDENCY" && /[/\]@sapper[/\]/.test(warning.message)) || onwarn(warning); // Define svelte-preprocess const preprocess = sveltePreprocess({ postcss: { plugins: [pimport, minmax, autoprefixer, csso], // --> add PostCSS plugins }, }); export default { client: { input: config.client.input(), output: config.client.output(), plugins: [ replace({ "process.browser": true, "process.env.NODE_ENV": JSON.stringify(mode), }), svelte({ dev, preprocess, // --> add sveltePreprocess hydratable: true, emitCss: true, }), resolve({ browser: true, dedupe: ["svelte"], }), commonjs(), legacy && babel({ extensions: [".js", ".mjs", ".html", ".svelte"], babelHelpers: "runtime", exclude: ["node_modules/@babel/**"], presets: [ [ "@babel/preset-env", { targets: "> 0.25%, not dead", }, ], ], plugins: [ "@babel/plugin-syntax-dynamic-import", [ "@babel/plugin-transform-runtime", { useESModules: true, }, ], ], }), !dev && terser({ module: true, }), ], preserveEntrySignatures: false, onwarn, }, server: { input: config.server.input(), output: config.server.output(), plugins: [ replace({ "process.browser": false, "process.env.NODE_ENV": JSON.stringify(mode), }), svelte({ generate: "ssr", preprocess, // --> add sveltePreprocess dev, }), resolve({ dedupe: ["svelte"], }), commonjs(), ], external: Object.keys(pkg.dependencies).concat( require("module").builtinModules || Object.keys(process.binding("natives")) ), preserveEntrySignatures: "strict", onwarn, }, serviceworker: { input: config.serviceworker.input(), output: config.serviceworker.output(), plugins: [ resolve(), replace({ "process.browser": true, "process.env.NODE_ENV": JSON.stringify(mode), }), commonjs(), !dev && terser(), ], preserveEntrySignatures: false, onwarn, }, };
Correct me please if I wrong, but with rollup.config.js
I not need to create separated svelte.config.js
file with only sveltePreprocess({...})
settings? 🤔
If I set lang
(or type
) attribute for <style>
to postcss
(or text/postcss
), I see the same error and very strange syntax highlighting to all CSS code:
Содержание
- Built-in Sass support not working. «Syntax error: Selector «body» is not pure» and other bullshit about non-pure selectors #16050
- Describe the bug
- To Reproduce
- Expected behavior
- System information
- Additional context
- Replies: 4 suggested answers · 4 replies
- Что означает ошибка SyntaxError: invalid syntax
- Что делать с ошибкой SyntaxError: invalid syntax
- Практика
- parsing — PHP parse/syntax errors; and how to solve them
- Answer
- Solution:
- What are the syntax errors?
- Most important tips
- How to interpret parser errors
- Solving syntax errors
- White screen of death
- Answer
- Solution:
- Using a syntax-checking IDE means:
- Answer
- Solution:
- Unexpected <-code-11>-code-1>
- Unexpected <-code-21>closing square bracket
- Answer
- Solution:
- Unexpected An "<-code-13<-code-16>unexpected <-code-1<-code-16>" <-code-13<-code-16>means that there’s a literal <-code-2<-code-16>name <-code-8<-code-16>which doesn’t fit into the current expression/statement structure Missing semicolon It most commonly indicates a missing semicolon in the previous line <-code-4<-code-16>Variable assignments following a statement are a good indicator where to look: String concatenation Btw <-code-8<-code-16>you should prefer string interpolation <-code-23>basic variables in double quotes) whenever that helps readability <-code-4<-code-16>Which avoids these syntax issues String interpolation is a scripting language core feature <-code-4<-code-16>No shame in utilizing it <-code-4<-code-16>Ignore any micro-optimization advise about variable <-code-4<-code-16>concatenation being faster <-code-4<-code-16>It’s not Missing expression operators Of course the same issue can arise in other expressions <-code-8<-code-16> <-code-14<-code-16>instance arithmetic operations: PHP can’t guess here <-code-19>the variable should have been added <-code-8<-code-16>subtracted or compared etc Lists Or functions parameter <-code-11<-code-16>s: Class declarations This parser error also occurs in class declarations <-code-4<-code-16>You can only assign static constants <-code-8<-code-16>not expressions <-code-4<-code-16>Thus the parser complains about variables as assigned data: Unmatched <-code-16>closing curly braces can in particular lead here <-code-4<-code-16>If a method is terminated too early <-code-23>use proper indentation!) <-code-8<-code-16>then a stray variable is commonly misplaced into the class declaration body Variables after ident<-code-19>iers Take in mind that using variable variables should be the exception <-code-4<-code-16>Newcomers often try to use them too casually <-code-8<-code-16>even when arrays would be simpler and more appropriate Missing parentheses after language constructs Hasty typing may lead to <-code-14<-code-16>gotten opening or closing parenthesis <-code-14<-code-16> <-code-19>and <-code-14<-code-16>and <-code-14<-code-16>each statements: Solution: add the missing opening <-code-23>between statement and variable The curly < brace does not open the code block<-code-8<-code-16>without closing the <-code-19>expression with the ) closing parenthesis first Else does not expect conditions Solution: Remove the conditions from else or use Need brackets <-code-14<-code-16>closure Solution: Add brackets around $var Invisible whitespace As mentioned in the reference answer on "<-code-13<-code-16>Invisible stray Unicode" <-code-13<-code-16><-code-23>such as a non-breaking space) <-code-8<-code-16>you might also see this error <-code-14<-code-16>unsuspecting code like: It’s rather prevalent in the start of files and <-code-14<-code-16>copy-and-pasted code <-code-4<-code-16>Check with a hexeditor <-code-8<-code-16> <-code-19>your code does not visually appear to contain a syntax issue See also Answer Solution: Unexpected T_CONSTANT_ENCAPSED_STRING Unexpected T_ENCAPSED_AND_WHITESPACE The unwieldy names T_CONSTANT_ENCAPSED_STRING and T_ENCAPSED_AND_WHITESPACE refer to quoted «string» literals. They’re used in different contexts, but the syntax issue are quite similar. T_ENCAPSED… warnings occur in double quoted string context, while T_CONSTANT… strings are often astray in plain PHP expressions or statements. Incorrect variable interpolation And it comes up most frequently for incorrect PHP variable interpolation: Quoting arrays keys is a must in PHP context. But in double quoted strings (or HEREDOCs) this is a mistake. The parser complains about the contained single quoted ‘string’ , because it usually expects a literal identifier / key there. More precisely it’s valid to use PHP2-style simple syntax within double quotes for array references: Nested arrays or deeper object references however require the complex curly string expression syntax: If unsure, this is commonly safer to use. It’s often even considered more readable. And better IDEs actually use distinct syntax colorization for that. Missing concatenation If a string follows an expression, but lacks a concatenation or other operator, then you’ll see PHP complain about the string literal: While it’s obvious to you and me, PHP just can’t guess that the string was meant to be appended there. Confusing string quote enclosures The same syntax error occurs when confounding string delimiters. A string started by a single ‘ or double » quote also ends with the same. That example started with double quotes. But double quotes were also destined for the HTML attributes. The intended concatenation operator within however became interpreted as part of a second string in single quotes. Tip: Set your editor/IDE to use slightly distinct colorization for single and double quoted strings. (It also helps with application logic to prefer e.g. double quoted strings for textual output, and single quoted strings only for constant-like values.) This is a good example where you shouldn’t break out of double quotes in the first place. Instead just use proper for the HTML attributesВґ quotes: While this can also lead to syntax confusion, all better IDEs/editors again help by colorizing the escaped quotes differently. Missing opening quote Here the ‘, ‘ would become a string literal after a bareword, when obviously login was meant to be a string parameter. Array lists If you miss a , comma in an array creation block, the parser will see two consecutive strings: Note that the last line may always contain an extra comma, but overlooking one in between is unforgivable. Which is hard to discover without syntax highlighting. Function parameter lists Runaway strings A common variation are quite simply forgotten string terminators: Here PHP complains about two string literals directly following each other. But the real cause is the unclosed previous string of course. HEREDOC indentation Prior PHP 7.3, the heredoc string end delimiter can’t be prefixed with spaces: Solution: upgrade PHP or find a better hoster. See also Answer Solution: Unexpected is a bit of a misnomer. It does not refer to a quoted <-code-2>. It means a raw identifier was encountered. This can range from <-code-3>words to leftover <-code-4>or function names, forgotten unquoted strings, or any plain text. Misquoted strings This syntax error is most common for misquoted string values however. Any unescaped and stray <-code-5>or <-code-6>quote will form an invalid expression: Syntax highlighting will make such mistakes super obvious. It<-code-6>s important to remember to use backslashes for escaping <-code-33> <-code-5>double quotes, or <-code-33> <-code-6>single quotes — depending on which was used as string enclosure. For convenience you should prefer outer single quotes when outputting plain HTML with double quotes within. Use double quoted strings if you want to interpolate variables, but then watch out for escaping literal <-code-5>double quotes. For lengthier output, prefer multiple <-code-11>/ <-code-12>lines instead of escaping in and out. Better yet consider a HEREDOC section. Another example is using PHP entry inside HTML code generated with PHP: This happens if <-code-14>is large with many lines and developer does not see the whole PHP variable value and focus on the piece of code forgetting about its source. Example is here Unclosed strings It<-code-6>s not just literal s which the parser may protest then. Another frequent variation is an for unquoted literal HTML. Non-programming string quotes If you copy and paste code from a blog or website, you sometimes end up with invalid code. Typographic quotes aren<-code-6>t what PHP expects: Typographic/smart quotes are Unicode symbols. PHP treats them as part of adjoining alphanumeric text. For example <-code-20>is interpreted as a constant identifier. But any following text literal is then seen as a <-code-3>word/ by the parser. The missing semicolon <-code-29>again If you have an unterminated expression in previous lines, then any following statement or language construct gets seen as raw identifier: PHP just can<-code-6>t know if you meant to run two functions after another, or if you meant to multiply their results, add them, compare them, or only run one <-code-22>or the other. Short open tags and <-code-23>headers in PHP scripts This is rather uncommon. But if short_open_tags are enabled, then you can<-code-6>t begin your PHP scripts with an XML declaration: Share solution ↓ Additional Information: Didn’t find the answer? Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free. Similar questions Find the answer in similar questions on our website. Write quick answer Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger. About the technologies asked in this question PHP (from the English Hypertext Preprocessor — hypertext preprocessor) is a scripting programming language for developing web applications. Supported by most hosting providers, it is one of the most popular tools for creating dynamic websites. The PHP scripting language has gained wide popularity due to its processing speed, simplicity, cross-platform, functionality and distribution of source codes under its own license. https://www.php.net/ Laravel Laravel is a free open source PHP framework that came out in 2011. Since then, it has been able to become the framework of choice for web developers. One of the main reasons for this is that Laravel makes it easier, faster, and safer to develop complex web applications than any other framework. https://laravel.com/ JavaScript JavaScript is a multi-paradigm language that supports event-driven, functional, and mandatory (including object-oriented and prototype-based) programming types. Originally JavaScript was only used on the client side. JavaScript is now still used as a server-side programming language. To summarize, we can say that JavaScript is the language of the Internet. https://www.javascript.com/ MySQL DBMS is a database management system. It is designed to change, search, add and delete information in the database. There are many DBMSs designed for similar purposes with different features. One of the most popular is MySQL. It is a software tool designed to work with relational SQL databases. It is easy to learn even for site owners who are not professional programmers or administrators. MySQL DBMS also allows you to export and import data, which is convenient when moving large amounts of information. https://www.mysql.com/ HTML (English «hyper text markup language» — hypertext markup language) is a special markup language that is used to create sites on the Internet. Browsers understand html perfectly and can interpret it in an understandable way. In general, any page on the site is html-code, which the browser translates into a user-friendly form. By the way, the code of any page is available to everyone. https://www.w3.org/html/ Welcome to programmierfrage.com programmierfrage.com is a question and answer site for professional web developers, programming enthusiasts and website builders. Site created and operated by the community. Together with you, we create a free library of detailed answers to any question on programming, web development, website creation and website administration. Get answers to specific questions Ask about the real problem you are facing. Describe in detail what you are doing and what you want to achieve. Help Others Solve Their Issues Our goal is to create a strong community in which everyone will support each other. If you find a question and know the answer to it, help others with your knowledge. Источник
- Missing semicolon
- String concatenation
- Missing expression operators
- Lists
- Class declarations
- Variables after ident<-code-19>iers
- Missing parentheses after language constructs
- Else does not expect conditions
- Need brackets <-code-14<-code-16>closure
- Invisible whitespace
- See also
- Answer
- Solution:
- Unexpected T_CONSTANT_ENCAPSED_STRING Unexpected T_ENCAPSED_AND_WHITESPACE
- Incorrect variable interpolation
- Missing concatenation
- Confusing string quote enclosures
- Missing opening quote
- Array lists
- Function parameter lists
- Runaway strings
- HEREDOC indentation
- Answer
- Solution:
- Unexpected
- Misquoted strings
- Unclosed strings
- Non-programming string quotes
- The missing semicolon <-code-29>again
- Short open tags and <-code-23>headers in PHP scripts
- Share solution ↓
- Additional Information:
- Didn’t find the answer?
- Similar questions
- Write quick answer
- About the technologies asked in this question
- Laravel
- JavaScript
- MySQL
- Welcome to programmierfrage.com
- Get answers to specific questions
- Help Others Solve Their Issues
Built-in Sass support not working. «Syntax error: Selector «body» is not pure» and other bullshit about non-pure selectors #16050
Tried to use built-in scss support but now I am getting the «Syntax error: Selector «body» is not pure» error when trying to compile a .module.scss file using built-in sass support.
Describe the bug
It happens when using pure css selectors like «body», «footer», «button» etc. (Also what the heck does «non-pure selector» even mean?? They seem pretty pure to me)
Though scss works fine if I am using class selectors instead of tag selectors.
To Reproduce
- install node 14.2.0
- install Next.js 9.5.1
- create Next.js project
- create a folder with .module.scss files in it, and add this code:
- install «sass»
- import scss module into jsx component
- shouldn’t compile
Expected behavior
It should not fire these errors and compile to css without problems, because its just a simple selector.
System information
- OS: Windows10
- Browser: Any
- Version of Next.js: [9.5.1]
- Version of Node.js: [14.2.0]
Additional context
Tried to reinstall: Next, node and sass.
Beta Was this translation helpful? Give feedback.
2 You must be logged in to vote
By design, CSS modules are scoped CSS classes and you’ll need to import them within a JS file and apply them to an HTML element’s className .
Example.module.scss
Example.js
Selectors like html , body , button , etc are global (unscoped) selectors; in addition they also are not valid scoped classes (like how .exampleClassName is scoped to a div element in the example above). Next expects CSS modules to be pure in that they don’t produce side effects (like altering the body style base…
The pure thing is about it being a css-module, which is not meant to be applied globally, but scoped to specific components.
And for that, targeting body doesn’t make sense.
You can leave the «module» part out (so, «style.scss») and import it your _app.js
Beta Was this translation helpful? Give feedback.
4 You must be logged in to vote
That doesn’t work if I want it to apply for a certain page.
Beta Was this translation helpful? Give feedback.
What «certain page» are you talking about?
Beta Was this translation helpful? Give feedback.
By design, CSS modules are scoped CSS classes and you’ll need to import them within a JS file and apply them to an HTML element’s className .
Example.module.scss
Example.js
Selectors like html , body , button , etc are global (unscoped) selectors; in addition they also are not valid scoped classes (like how .exampleClassName is scoped to a div element in the example above). Next expects CSS modules to be pure in that they don’t produce side effects (like altering the body style based upon a page being loaded or a particular component being loaded — in the example above, the body is outside of the component-level scope). The reason pure stylesheets are enforced/encouraged is because they allow CSS to be split chunked (when you land on a page, you only download the styles necessary to view that particular page, instead of downloading everything at once).
Imagine you have 2 components that both alter the body style, where one sets overflow: hidden; and the other sets overflow: scroll; . Which one takes precedence? On the same note, what if one component is loaded before the other component, which one should take precedence then? These global style overrides can produce inconsistent UIs based upon a user’s action and/or when the stylesheets are downloaded. Therefore, using scoped modules helps eliminate these style collisions.
If you wish to use global selectors, then you should use a global stylesheet.
Please refer to the css-modules documentation for more information.
Beta Was this translation helpful? Give feedback.
Источник
Что означает ошибка SyntaxError: invalid syntax
Когда Python не может разобраться в ваших командах
Ситуация: программист взял в работу математический проект — ему нужно написать код, который будет считать функции и выводить результаты. В задании написано:
«Пусть у нас есть функция f(x,y) = xy, которая перемножает два аргумента и возвращает полученное значение».
Программист садится и пишет код:
Но при выполнении такого кода компьютер выдаёт ошибку:
File «main.py», line 13
result = x y
^
❌ SyntaxError: invalid syntax
Почему так происходит: в каждом языке программирования есть свой синтаксис — правила написания и оформления команд. В Python тоже есть свой синтаксис, по которому для умножения нельзя просто поставить рядом две переменных, как в математике. Интерпретатор находит первую переменную и думает, что ему сейчас объяснят, что с ней делать. Но вместо этого он сразу находит вторую переменную. Интерпретатор не знает, как именно нужно их обработать, потому что у него нет правила «Если две переменные стоят рядом, их нужно перемножить». Поэтому интерпретатор останавливается и говорит, что у него лапки.
Что делать с ошибкой SyntaxError: invalid syntax
В нашем случае достаточно поставить звёздочку (знак умножения в Python) между переменными — это оператор умножения, который Python знает:
В общем случае найти источник ошибки SyntaxError: invalid syntax можно так:
- Проверьте, не идут ли у вас две команды на одной строке друг за другом.
- Найдите в справочнике описание команды, которую вы хотите выполнить. Возможно, где-то опечатка.
- Проверьте, не пропущена ли команда на месте ошибки.
Практика
Попробуйте найти ошибки в этих фрагментах кода:
Источник
parsing — PHP parse/syntax errors; and how to solve them
Everyone runs into syntax errors. Even experienced programmers make typos. For newcomers, it’s just part of the learning process. However, it’s often easy to interpret error messages such as:
PHP Parse error: syntax error, unexpected ‘<-code-1>‘ in index.php on line 20
The unexpected symbol isn’t always the real culprit. But the line number gives a rough idea of where to start looking.
Always look at the code context. The syntax mistake often hides in the mentioned or in previous code lines. Compare your code against syntax examples from the manual.
While not every case matches the other. Yet there are some general steps to . This references summarized the common pitfalls:
Closely related references:
While Stack Overflow is also welcoming rookie coders, it’s mostly targetted at professional programming questions.
- Answering everyone’s coding mistakes and narrow typos is considered mostly off-topic.
- So please take the time to follow the basic steps, before posting syntax fixing requests.
- If you still have to, please show your own solving initiative, attempted fixes, and your thought process on what looks or might be wrong.
If your browser displays error messages such as «SyntaxError: illegal character», then it’s not actually php-related, but a javascript-syntax error.
Syntax errors raised on vendor code: Finally, consider that if the syntax error was not raised by editing your codebase, but after an external vendor package install or upgrade, it could be due to PHP version incompatibility, so check the vendor’s requirements against your platform setup.
Answer
Solution:
What are the syntax errors?
PHP belongs to the C-style and imperative programming languages. It has rigid grammar rules, which it cannot recover from when encountering misplaced symbols or ident<-code-18>-code-11>iers. It can<-code-18>-code-8>t guess your coding intentions.
Most important tips
There are a few basic precautions you can always take:
Use proper code indentation, or adopt any lofty coding style. Readability prevents irregularities.
Read the language reference and examples in the manual. Twice, to become somewhat proficient.
How to interpret parser errors
A typical syntax error message reads:
Parse error: syntax error, unexpected <-code-18>-code-4<-code-18>-code-5>-code-2<-code-18>-code-5>, expecting <-code-18>-code-8> <-code-18>-code-4<-code-18>-code-5>-code-1<-code-18>-code-5> <-code-18>-code-8> in file.php on line 217
Which lists the possible location of a syntax mistake. See the mentioned file name and line number.
A moniker such as <-code-18>-code-4<-code-18>-code-5>-code-2<-code-18>-code-5> explains which symbol the parser/tokenizer couldn<-code-18>-code-8>t process finally. This isn<-code-18>-code-8>t necessarily the cause of the syntax mistake, however.
It<-code-18>-code-8>s important to look into previous code lines as well. Often syntax errors are just mishaps that happened earlier. The error line number is just where the parser conclusively gave up to process it all.
Solving syntax errors
There are many approaches to narrow down and fix syntax hiccups.
Open the mentioned source file. Look at the mentioned code line.
For runaway strings and misplaced operators, this is usually where you find the culprit.
Read the line left to right and imagine what each symbol does.
More regularly you need to look at preceding lines as well.
In particular, missing <-code-18>-code-4<-code-18>-code-5>-code-1<-code-18>-code-5> semicolons are missing at the previous line ends/statement. (At least from the stylistic viewpoint. )
If <-code-18>-code-4<-code-18>-code-5> code blocks <-code-18>-code-5> are incorrectly closed or nested, you may need to investigate even further up the source code. Use proper code indentation to simpl<-code-18>-code-11>y that.
Look at the syntax colorization!
Strings and variables and constants should all have d<-code-18>-code-11>ferent colors.
Operators <-code-18>-code-6> should be tinted distinct as well. Else they might be in the wrong context.
If you see string colorization extend too far or too short, then you have found an unescaped or missing closing <-code-18>-code-7> or <-code-18>-code-8> string marker.
Having two same-colored punctuation characters next to each other can also mean trouble. Usually, operators are lone <-code-18>-code-11> it<-code-18>-code-8>s not <-code-18>-code-9> , <-code-18>-code-10> , or parentheses following an operator. Two strings/ident<-code-18>-code-11>iers directly following each other are incorrect in most contexts.
Whitespace is your friend. Follow any coding style.
Break up long lines temporarily.
You can freely add newlines between operators or constants and strings. The parser will then concretize the line number for parsing errors. Instead of looking at the very lengthy code, you can isolate the missing or misplaced syntax symbol.
Split up complex <-code-18>-code-11> statements into distinct or nested <-code-18>-code-11> conditions.
Instead of lengthy math formulas or logic chains, use temporary variables to simpl<-code-18>-code-11>y the code. (More readable = fewer errors.)
Add newlines between:
- The code you can easily ident<-code-18>-code-11>y as correct,
- The parts you<-code-18>-code-8>re unsure about,
- And the lines which the parser complains about.
Partitioning up long code blocks really helps to locate the origin of syntax errors.
Comment out offending code.
If you can<-code-18>-code-8>t isolate the problem source, start to comment out (and thus temporarily remove) blocks of code.
As soon as you got rid of the parsing error, you have found the problem source. Look more closely there.
Sometimes you want to temporarily remove complete function/method blocks. (In case of unmatched curly braces and wrongly indented code.)
When you can<-code-18>-code-8>t resolve the syntax issue, try to rewrite the commented out sections from scratch.
As a newcomer, avoid some of the confusing syntax constructs.
The ternary <-code-18>-code-13> condition operator can compact code and is useful indeed. But it doesn<-code-18>-code-8>t aid readability in all cases. Prefer plain <-code-18>-code-11> statements while unversed.
PHP<-code-18>-code-8>s alternative syntax ( <-code-18>-code-11>: / else<-code-18>-code-11>: / end<-code-18>-code-11><-code-18>-code-4<-code-18>-code-5>-code-1<-code-18>-code-5> ) is common for templates, but arguably less easy to follow than normal <-code-18>-code-4<-code-18>-code-5> code <-code-18>-code-5> blocks.
The most prevalent newcomer mistakes are:
Missing semicolons <-code-18>-code-4<-code-18>-code-5>-code-1<-code-18>-code-5> for terminating statements/lines.
Mismatched string quotes for <-code-18>-code-7> or <-code-18>-code-8> and unescaped quotes within.
Forgotten operators, in particular for the string . concatenation.
Unbalanced ( parentheses ) . Count them in the reported line. Are there an equal number of them?
Don<-code-18>-code-8>t forget that solving one syntax problem can uncover the next.
If you make one issue go away, but other crops up in some code below, you<-code-18>-code-8>re mostly on the right path.
If after editing a new syntax error crops up in the same line, then your attempted change was possibly a failure. (Not always though.)
Restore a backup of previously working code, <-code-18>-code-11> you can<-code-18>-code-8>t fix it.
- Adopt a source code versioning system. You can always view a d<-code-18>-code-11>f of the broken and last working version. Which might be enlightening as to what the syntax problem is.
Invisible stray Unicode characters: In some cases, you need to use a hexeditor or d<-code-18>-code-11>ferent editor/viewer on your source. Some problems cannot be found just from looking at your code.
In particular BOMs, zero-width spaces, or non-breaking spaces, and smart quotes regularly can find their way into the source code.
Take care of which type of linebreaks are saved in files.
PHP just honors n newlines, not r carriage returns.
Which is occasionally an issue for MacOS users (even on OS <-code-18>-code-4<-code-18>-code-5>-code-1<-code-18>-code-5> X for misconfigured editors).
It often only surfaces as an issue when single-line // or # comments are used. Multiline /*. */ comments do seldom disturb the parser when linebreaks get ignored.
If your syntax error does not transmit over the web: It happens that you have a syntax error on your machine. But posting the very same file online does not exhibit it anymore. Which can only mean one of two things:
You are looking at the wrong file!
Or your code contained invisible stray Unicode (see above). You can easily find out: Just copy your code back from the web form into your text editor.
Check your PHP version. Not all syntax constructs are available on every server.
php -v for the command line interpreter
<<-code-18>-code-4<-code-18>-code-5>-code-1<-code-18>-code-5>?php phpinfo()<-code-18>-code-4<-code-18>-code-5>-code-1<-code-18>-code-5> for the one invoked through the webserver.
Those aren<-code-18>-code-8>t necessarily the same. In particular when working with frameworks, you will them to match up.
Don<-code-18>-code-8>t use PHP<-code-18>-code-8>s reserved keywords as ident<-code-18>-code-11>iers for functions/methods, classes or constants.
Trial-and-error is your last resort.
If all else fails, you can always google your error message. Syntax symbols aren<-code-18>-code-8>t as easy to search for (Stack Overflow itself is indexed by SymbolHound though). Therefore it may take looking through a few more pages before you find something relevant.
White screen of death
If your website is just blank, then typically a syntax error is the cause. Enable their display with:
- error_reporting = E_ALL
- display_errors = 1
Enabling it within the broken script is too late because PHP can<-code-18>-code-8>t even interpret/run the first line. A quick workaround is crafting a wrapper script, say test.php :
Then invoke the failing code by accessing this wrapper script.
Answer
Solution:
I think this topic is totally overdiscussed/overcomplicated. Using an IDE is THE way to go to completely avoid any syntax errors. I would even say that working without an IDE is kind of unprofessional. Why? Because modern IDEs check your syntax after every character you type. When you code and your entire line turns red, and a big warning notice shows you the exact type and the exact position of the syntax error, then there’s absolutely no need to search for another solution.
Using a syntax-checking IDE means:
You’ll (effectively) never run into syntax errors again, simply because you see them right as you type. Seriously.
Excellent IDEs with syntax check (all of them are available for Linux, Windows and Mac):
Answer
Solution:
Unexpected <-code-11>-code-1>
These days, the unexpected <-code-11>-code-1> array bracket is commonly seen on outdated PHP versions. The short array syntax is available since PHP >= 5.4. Older installations only support <-code-11>-code-3> .
Array function result dereferencing is likewise not available for older PHP versions:
Though, you’re always better off just upgrading your PHP installation. For shared webhosting plans, first research if e.g. <-code-11>-code-7> can be used to enable a newer runtime.
BTW, there are also preprocessors and PHP 5.4 syntax down-converters if you’re really clingy with older + slower PHP versions.
Other causes for Unexpected <-code-11>-code-1> syntax errors
If it’s not the PHP version mismatch, then it’s oftentimes a plain typo or newcomer syntax mistake:
Confusing <-code-11>-code-1> with opening curly braces <-code-11>or parentheses <-code-12>is a common oversight.
Or trying to dereference <-code-16>ants <-code-12>before PHP 5.6 <-code-23>as arrays:
At least PHP interprets that <-code-16>as a <-code-16>ant name.
If you meant to access an array variable <-code-12>which is the typical cause here<-code-23>, then add the leading <-code-17>sigil — so it becomes a <-code-17>varname .
You are trying to use the <-code-19>keyword on a member of an associative array. This is not valid syntax:
Unexpected <-code-21>closing square bracket
This is somewhat rarer, but there are also syntax accidents with the terminating array <-code-21>bracket.
Again mismatches with <-code-23>parentheses or > curly braces are common:
Or trying to end an array where there isn’t one:
Which often occurs in multi-line and nested array declarations.
If so, use your IDE for bracket matching to find any premature <-code-21>array closure. At the very least use more spacing and newlines to narrow it down.
Answer
Solution:
Unexpected
An "<-code-13<-code-16>unexpected <-code-1<-code-16>" <-code-13<-code-16>means that there’s a literal <-code-2<-code-16>name <-code-8<-code-16>which doesn’t fit into the current expression/statement structure
Missing semicolon
It most commonly indicates a missing semicolon in the previous line <-code-4<-code-16>Variable assignments following a statement are a good indicator where to look:
String concatenation
Btw <-code-8<-code-16>you should prefer string interpolation <-code-23>basic variables in double quotes) whenever that helps readability <-code-4<-code-16>Which avoids these syntax issues
String interpolation is a scripting language core feature <-code-4<-code-16>No shame in utilizing it <-code-4<-code-16>Ignore any micro-optimization advise about variable <-code-4<-code-16>concatenation being faster <-code-4<-code-16>It’s not
Missing expression operators
Of course the same issue can arise in other expressions <-code-8<-code-16> <-code-14<-code-16>instance arithmetic operations:
PHP can’t guess here <-code-19>the variable should have been added <-code-8<-code-16>subtracted or compared etc
Lists
Or functions parameter <-code-11<-code-16>s:
Class declarations
This parser error also occurs in class declarations <-code-4<-code-16>You can only assign static constants <-code-8<-code-16>not expressions <-code-4<-code-16>Thus the parser complains about variables as assigned data:
Unmatched <-code-16>closing curly braces can in particular lead here <-code-4<-code-16>If a method is terminated too early <-code-23>use proper indentation!) <-code-8<-code-16>then a stray variable is commonly misplaced into the class declaration body
Variables after ident<-code-19>iers
Take in mind that using variable variables should be the exception <-code-4<-code-16>Newcomers often try to use them too casually <-code-8<-code-16>even when arrays would be simpler and more appropriate
Missing parentheses after language constructs
Hasty typing may lead to <-code-14<-code-16>gotten opening or closing parenthesis <-code-14<-code-16> <-code-19>and <-code-14<-code-16>and <-code-14<-code-16>each statements:
Solution: add the missing opening <-code-23>between statement and variable
The curly < brace does not open the code block<-code-8<-code-16>without closing the <-code-19>expression with the ) closing parenthesis first
Else does not expect conditions
Solution: Remove the conditions from else or use
Need brackets <-code-14<-code-16>closure
Solution: Add brackets around $var
Invisible whitespace
As mentioned in the reference answer on "<-code-13<-code-16>Invisible stray Unicode" <-code-13<-code-16><-code-23>such as a non-breaking space) <-code-8<-code-16>you might also see this error <-code-14<-code-16>unsuspecting code like:
It’s rather prevalent in the start of files and <-code-14<-code-16>copy-and-pasted code <-code-4<-code-16>Check with a hexeditor <-code-8<-code-16> <-code-19>your code does not visually appear to contain a syntax issue
See also
Answer
Solution:
Unexpected T_CONSTANT_ENCAPSED_STRING
Unexpected T_ENCAPSED_AND_WHITESPACE
The unwieldy names T_CONSTANT_ENCAPSED_STRING and T_ENCAPSED_AND_WHITESPACE refer to quoted «string» literals.
They’re used in different contexts, but the syntax issue are quite similar. T_ENCAPSED… warnings occur in double quoted string context, while T_CONSTANT… strings are often astray in plain PHP expressions or statements.
Incorrect variable interpolation
And it comes up most frequently for incorrect PHP variable interpolation:
Quoting arrays keys is a must in PHP context. But in double quoted strings (or HEREDOCs) this is a mistake. The parser complains about the contained single quoted ‘string’ , because it usually expects a literal identifier / key there.
More precisely it’s valid to use PHP2-style simple syntax within double quotes for array references:
Nested arrays or deeper object references however require the complex curly string expression syntax:
If unsure, this is commonly safer to use. It’s often even considered more readable. And better IDEs actually use distinct syntax colorization for that.
Missing concatenation
If a string follows an expression, but lacks a concatenation or other operator, then you’ll see PHP complain about the string literal:
While it’s obvious to you and me, PHP just can’t guess that the string was meant to be appended there.
Confusing string quote enclosures
The same syntax error occurs when confounding string delimiters. A string started by a single ‘ or double » quote also ends with the same.
That example started with double quotes. But double quotes were also destined for the HTML attributes. The intended concatenation operator within however became interpreted as part of a second string in single quotes.
Tip: Set your editor/IDE to use slightly distinct colorization for single and double quoted strings. (It also helps with application logic to prefer e.g. double quoted strings for textual output, and single quoted strings only for constant-like values.)
This is a good example where you shouldn’t break out of double quotes in the first place. Instead just use proper for the HTML attributesВґ quotes:
While this can also lead to syntax confusion, all better IDEs/editors again help by colorizing the escaped quotes differently.
Missing opening quote
Here the ‘, ‘ would become a string literal after a bareword, when obviously login was meant to be a string parameter.
Array lists
If you miss a , comma in an array creation block, the parser will see two consecutive strings:
Note that the last line may always contain an extra comma, but overlooking one in between is unforgivable. Which is hard to discover without syntax highlighting.
Function parameter lists
Runaway strings
A common variation are quite simply forgotten string terminators:
Here PHP complains about two string literals directly following each other. But the real cause is the unclosed previous string of course.
HEREDOC indentation
Prior PHP 7.3, the heredoc string end delimiter can’t be prefixed with spaces:
Solution: upgrade PHP or find a better hoster.
See also
Answer
Solution:
Unexpected
is a bit of a misnomer. It does not refer to a quoted <-code-2>. It means a raw identifier was encountered. This can range from <-code-3>words to leftover <-code-4>or function names, forgotten unquoted strings, or any plain text.
Misquoted strings
This syntax error is most common for misquoted string values however. Any unescaped and stray <-code-5>or <-code-6>quote will form an invalid expression:
Syntax highlighting will make such mistakes super obvious. It<-code-6>s important to remember to use backslashes for escaping <-code-33> <-code-5>double quotes, or <-code-33> <-code-6>single quotes — depending on which was used as string enclosure.
- For convenience you should prefer outer single quotes when outputting plain HTML with double quotes within.
- Use double quoted strings if you want to interpolate variables, but then watch out for escaping literal <-code-5>double quotes.
- For lengthier output, prefer multiple <-code-11>/ <-code-12>lines instead of escaping in and out. Better yet consider a HEREDOC section.
Another example is using PHP entry inside HTML code generated with PHP:
This happens if <-code-14>is large with many lines and developer does not see the whole PHP variable value and focus on the piece of code forgetting about its source. Example is here
Unclosed strings
It<-code-6>s not just literal s which the parser may protest then. Another frequent variation is an for unquoted literal HTML.
Non-programming string quotes
If you copy and paste code from a blog or website, you sometimes end up with invalid code. Typographic quotes aren<-code-6>t what PHP expects:
Typographic/smart quotes are Unicode symbols. PHP treats them as part of adjoining alphanumeric text. For example <-code-20>is interpreted as a constant identifier. But any following text literal is then seen as a <-code-3>word/ by the parser.
The missing semicolon <-code-29>again
If you have an unterminated expression in previous lines, then any following statement or language construct gets seen as raw identifier:
PHP just can<-code-6>t know if you meant to run two functions after another, or if you meant to multiply their results, add them, compare them, or only run one <-code-22>or the other.
Short open tags and <-code-23>headers in PHP scripts
This is rather uncommon. But if short_open_tags are enabled, then you can<-code-6>t begin your PHP scripts with an XML declaration:
Additional Information:
Didn’t find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.
About the technologies asked in this question
PHP (from the English Hypertext Preprocessor — hypertext preprocessor) is a scripting programming language for developing web applications. Supported by most hosting providers, it is one of the most popular tools for creating dynamic websites. The PHP scripting language has gained wide popularity due to its processing speed, simplicity, cross-platform, functionality and distribution of source codes under its own license.
https://www.php.net/
Laravel
Laravel is a free open source PHP framework that came out in 2011. Since then, it has been able to become the framework of choice for web developers. One of the main reasons for this is that Laravel makes it easier, faster, and safer to develop complex web applications than any other framework.
https://laravel.com/
JavaScript
JavaScript is a multi-paradigm language that supports event-driven, functional, and mandatory (including object-oriented and prototype-based) programming types. Originally JavaScript was only used on the client side. JavaScript is now still used as a server-side programming language. To summarize, we can say that JavaScript is the language of the Internet.
https://www.javascript.com/
MySQL
DBMS is a database management system. It is designed to change, search, add and delete information in the database. There are many DBMSs designed for similar purposes with different features. One of the most popular is MySQL. It is a software tool designed to work with relational SQL databases. It is easy to learn even for site owners who are not professional programmers or administrators. MySQL DBMS also allows you to export and import data, which is convenient when moving large amounts of information.
https://www.mysql.com/
HTML (English «hyper text markup language» — hypertext markup language) is a special markup language that is used to create sites on the Internet. Browsers understand html perfectly and can interpret it in an understandable way. In general, any page on the site is html-code, which the browser translates into a user-friendly form. By the way, the code of any page is available to everyone.
https://www.w3.org/html/
Welcome to programmierfrage.com
programmierfrage.com is a question and answer site for professional web developers, programming enthusiasts and website builders. Site created and operated by the community. Together with you, we create a free library of detailed answers to any question on programming, web development, website creation and website administration.
Get answers to specific questions
Ask about the real problem you are facing. Describe in detail what you are doing and what you want to achieve.
Help Others Solve Their Issues
Our goal is to create a strong community in which everyone will support each other. If you find a question and know the answer to it, help others with your knowledge.
Источник
Skip to content
In action
You gonna need nodejs and then install CSSlint:
sudo npm install -g csslint
CSSlint options:
$ csslint Usage: csslint-rhino.js [options]* [file|dir]* Global Options --help Displays this information. --format= Indicate which format to use for output. --list-rules Outputs all of the rules available. --quiet Only output when errors are present. --errors=<rule[,rule]+> Indicate which rules to include as errors. --warnings=<rule[,rule]+> Indicate which rules to include as warnings. --ignore=<rule[,rule]+> Indicate which rules to ignore completely. --exclude-list=<file|dir[,file|dir]+> Indicate which files/directories to exclude from being linted. --version Outputs the current version number.
Next comes the VIM plugin Syntastic. The installation process requires a plugin manager. The README uses pathogen so I stayed with it.
So first install pathogen:
$ mkdir -p ~/.vim/autoload ~/.vim/bundle $ curl -LSso ~/.vim/autoload/pathogen.vim https://tpo.pe/pathogen.vim
Next edit and add to ~/.vimrc:
execute pathogen#infect()
Finally download syntastic:
cd ~/.vim/bundle git clone https://github.com/scrooloose/syntastic.git
I added this line to my ~/.vimrc
let g:syntastic_csslint_args="--ignore=outline-none"
For a complete list of rules execute:
csslint --list-rules
Full stack developer, biker and rollerblader.
Owner and developer at https://nevilleweb.sk/
Co-founded http://neville.sk/
Blog at https://michalzuber.wordpress.com/
View all posts by Michal Zuber