I have an issue here, and I'm looking for experienced programmers to tell me which is the preferred solution.
I have values being returned that are surrounded in quotes. "TOTAL" and "VALUE" being two examples. These should not be confused with TOTAL and VALUE -- the string is actually surrounded by double quotes.
What I noticed is that the switch statement below doesn't work because it's looking for TOTAL not "TOTAL":
switch ($statTypeName) {
case "TOTAL":
echo "<br>TOTAL";
break;
case "VALUE":
echo "<br>VALUE";
break;
}
To get this working, I had to put a single quote around the case -- '"TOTAL"'.
In my text editor (Notepad++), it is difficult to see the single quote around the double quotes.
I know this isn't a common issue, but what would be the "professional" way of solving this? The way I did it, or should I be extracting the string from the quoted string and do away with the double quotes altogether..?
Thanks!
case "\"TOTAL\"":
Escape the inner double quotes. It will work the same way and might be a little more visible to the reader
What you're running into is indeed common, and you can go about it a couple different ways. There's nothing wrong with the way you're doing it, or #KyleBanks solution (escaping the double quotes). Given php provides single and double quote string definitions, I prefer the first. But its up to your preference, or your dev team.
As far as extracting the substring within the string quotes.. it depends on what they're there for in the first place.
I would suggest using a better font in Notepad++. I personally use Consolas however here you can find heaps of other good options:
Recommended Fonts for Programming?
Other then changing font escaping quotes as was suggested is another alternative:
case "\"TOTAL\"":
You can also try to strip quotes:
switch (substr($statTypeName, 1, -1)) {...}
but i consider it as a more dangerous approach unless you start using more complicated code to strip them with checks and everything in which case it clearly becomes an overkill.
Except if your given code is not part of some kind of StatType class and is dealing internally with the representation of stat type states my answer might be missing the point a bit, but in any case here it is.
In fact you are doing something wrong here and what you are asking is to find a way to workaround the essential problem you are having. Instead, you should fix the essential problem.
Essential problem is that you are missing one layer of abstraction which will sit between the way you are representing your statType and the way you are using it.
So, your program should not care if you call your statType:
"TOTAL" or '"TOTAL"' or "Total" or "total"
What you need to care is that your statType is in certain state in one moment of program execution. How that representation of the state is implemented ( a string with quotes or a number) is detail of implementation and your switch statement should not care about it.
What happens if you decide to change your statTypeName to be without quotes for example. Than you'll have to go to every line of code that depended on it having quotes and to change it. If you would hide the implementation details in some way you would not need to change more than one line of code.
Maybe one approach to setting abstraction around statTypes? (simplified for clarity)
class StatType
{
const TOTAL = 0;
const VALUE = 1;
// etc.
}
switch ($statType->type()) {
case StatType::TOTAL:
echo "<br>TOTAL";
break;
case StatType::VALUE:
echo "<br>VALUE";
break;
}
Related
I am trying to convert a single quote into html specialchars.. but its not working. I am not sure what I am doing wrong here. Below is how I am using the function
echo htmlspecialchars("Housemade Mac N' Cheese",ENT_QUOTES);
Any help would be really appreciated!
The following comes from my own experiment.
Try this, it will replace all single quote by ߴ, which is an Unicode character. nko high tone apostrophe (U+07F4). Php/js will treat it as a regular character, so no headaches here.
Of course the content of $string is going to be altered, this is not the perfect solution but a workaround.
echo htmlspecialchars(preg_replace("/'/","ߴ",$string),ENT_QUOTES);
To understand it better, in your showcase, the following should be ok, but what if the string will change to something you don't know yet. Will it contains single quotes, on, two, three, where? This is hard stuff! Look simple but it is actually a very complex case!
echo htmlspecialchars("Housemade Mac N\' Cheese",ENT_QUOTES);
Philosophical annexe, this part can be skipped...
The most complex things are hiding in the simplest.
Personal reflexion 💡
There is probably a much more elegant way to say the title, but that's the best I could come up with because frankly I am feeling silly that I don't know the answer and even have to ask but that's how you learn, so no shame necessary.
I have stored dataURIs such as :
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAYAAABXAvmHAAAE5klEQVR4nO1ZS0hjVxg+9xEJVFAnCzcuurVC3XfTWpqMMTGJbrSFQumAxhERFdE4YK4Bo5kY8zAvo0434nKghW46pXRhH5sKBXHXdikyDjGK0ETj7f/f5KY3N68bySSh9YPP/5x7Xv9/znfOubkS8oAH/L9B1XtAnufVYNTZbBqYpCgqVaKuCgySxiwwBXVvpHXYt+hrKajn5+fjNzc3hGEYolarT1ZXV0NLS0t74FwSK4DjLQ6H48nCwsJkKpXqSafTQl2v19sKxQ0PIAcM4vr6+r2rq6uQzWZ7ur+//8nd3R1ZXFz8Hp73YDnLsoSmaQwKm/DyPuj6u03+drvd7Z2dnf1dXV2fazSaX2DmSSKR6Dk+Pn55c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FDOp3upbI3I34VoWn695aWlr5AIBAv177uewA0TjscDs3U1FQf8MuLi4sjdF5whqZnkRgIBNGbTCaPYDW+GB8f/6hUf434Nkqdnp6ei//MEP+hAbp3wGUofLWC+6ANjB3K3gV+hc9AWiQWixUopqGnEDoOrxnfAD+GTWuHPI+MRqMc2D7g1xX7qIejUqCEJOMKL1/odL39eMAD/iv4B7EvTT8yUT9VAAAAAElFTkSuQmCC
in a variable by simply doing: $some_var = "INSERT_ABOVE"; and has usually worked fine, but I am finding in a piece of code I am working on right now that the code breaks anytime one of the variable=>datauri scheme I showed above is used but deleting that line, fixes the code.
So I am not sure ?WHY? this particular datauri is breaking the code and shouldn't anything inside "" QUOTATIONS be treated as a literal string? Is there a best practice or should I say recommended way of storing datauris as variables to be used through the code, so it doesn't break?
Any thoughts and/or suggestions would be greatly appreciated, TIA.
PS. This wasn't just due to the backslash at the end, it was also that the string by itself wasn't being respected, now it is storing into variable like this, thanks. Since the title most accurately describes what was being achieved, I think its more appropriate.
Use Heredoc string quoting. It's another way to represent strings in PHP. It can eliminate your problem of ending quote getting escaped by string data.
$str = <<<EOD
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAYAAABXAvmHAAAE5klEQVR4nO1ZS0hjVxg+9xEJVFAnCzcuurVC3XfTWpqMMTGJbrSFQumAxhERFdE4YK4Bo5kY8zAvo0434nKghW46pXRhH5sKBXHXdikyDjGK0ETj7f/f5KY3N68bySSh9YPP/5x7Xv9/znfOubkS8oAH/L9B1XtAnufVYNTZbBqYpCgqVaKuCgySxiwwBXVvpHXYt+hrKajn5+fjNzc3hGEYolarT1ZXV0NLS0t74FwSK4DjLQ6H48nCwsJkKpXqSafTQl2v19sKxQ0PIAcM4vr6+r2rq6uQzWZ7ur+//8nd3R1ZXFz8Hp73YDnLsoSmaQwKm/DyPuj6u03+drvd7Z2dnf1dXV2fazSaX2DmSSKR6Dk+Pn55cnLy8vLysgeftbW1/Qz1Puvo6ND5fL53iGz2EXXfA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1FQf8MuLi4sjdF5whqZnkRgIBNGbTCaPYDW+GB8f/6hUf434Nkqdnp6ei//MEP+hAbp3wGUofLWC+6ANjB3K3gV+hc9AWiQWixUopqGnEDoOrxnfAD+GTWuHPI+MRqMc2D7g1xX7qIejUqCEJOMKL1/odL39eMAD/iv4B7EvTT8yUT9VAAAAAElFTkSuQmCC\
EOD;
echo $str;
Are there any issues I should be aware of when doing the following:
$table_html = ' <td id="unescaped-double-quotes-yay">Some stuff</td>' . "\n";
I do not like escaping double quotes withing HTML and I can't stand using single quotes in HTML, my solution is what I have above. Am I going to run into any issues with this practice?
You MUST escape strings that comes from DB or from the user because they could easily break you concatenation if the unexpected kind of quote is present in that string (not to mention that you MUST cleanse anything that comes from the user for minimal security).
Other than that you can concatenate strings any way you like. Still, life will always be easier if you manage to use them cosistently the same way.
I have done this many times on client sites (have since found better alternatives), you are 100% fine.
Are you aware of the following representation:
$table_html = <<<HTML
<td id="unescaped-double-quotes-yay">
Some stuff, and i can use normal newlines here
</td>
HTML;
It is called "heredoc", and you must keep in mind that the final string must be equivalent to the opening one, and must be the only thing on the line (no spaces or even comments are allowed).
You must also terminate the last line with the newline, even if it is the last line in the file.
To read more about it click here
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
Is it better to concatenate a variable (say, $name) into an existing string (say, $string) like this:
$string='Hi, my name is '.$name
or to embed the variable in the string like this:
$string="Hi, my name is $name";
or is it better to use a function like this:
$string=sprintf("Hi, my name is %s",$name);
Which is better in terms of processor time/efficiency?
Everyone who did the test concluded that using single quotes is marginally better performance wise. In the end single quotes result in just a concatenation while double quotes forces the interpreter to parse the complete string for variables.
However the added load in doing that is so small for the last versions of PHP that most of the time the conclusion is that it doesn't really matter.
So for the performance people: use single quotes. For the "i like my code readable"-people: double quotes are a lot better for the legibility, as Flavius Stef already pointed out.
Edit: One thing though - If you are going to use a a single dollar in your string without a variable, use single quotes for sure! (http://www.weberdev.com/get_example-3750.html points out that it will take 4 times longer to parse those strings)
The difference between single and double quotes in PHP is that double quotes are "intelligent" in that they will parse for variables when being read, while single quotes are "dumb" and will not try to parse any character in the string.
These result in some minor differences in what characters you can use; basically, the only character you need to escape when using single quotes is a single quote itself:
'\''
While if you use double quotes you have to escape other characters:
"\$"
But it also allows for some nifty things like adding a new-line to the end:
"my string\n"
With single quotes you would have to do a concatenation:
'my string' . chr(10)
'my string' . "\n"
Generally, single quotes are faster because they are "dumb".
However, normally one should not really worry about these issues, that is called Premature optimization, and should be avoided.
A couple of words about optimization: generally one should first write the program the way it should work, and then find the biggest bottlenecks and fix those particular ones. If string speed really is an issue for you in PHP, you might want to consider switching to another language.
Regarding speed: you probably want to focus more on memory usage than on CPU time. In these cases the CPU time could be considered pretty constant. CPU time is more relevant when writing algorithms that will iterate many times.
Regarding concatenations: the more you concatenate strings using the dot-operator, the more memory you will be using.
Consider this:
$str1 = 'asdf';
$str2 = 'qwer';
// this will result in more memory being allocated for temporary storage
echo $str1 . $str2;
// this will not allocate as much memory as the previous example
echo $str1;
echo $str2;
I generally feel that using string interpolation ("Hi, my name is $name") is better from a legibility standpoint.
For performance, as others have proven, it is marginally faster to use single quotes rather than double quotes.
Single quotes, if applied to readability science and kept away from subjectivity actually adds more "noise". Noise and how it relates to readability is talked a lot about in the book Clean Code and one could conclude that the more non-whitespace you have to see, the more it hinders readability. If applied to subjectivity, most places that I've taken the time to read actually prefer single over double quotes.
Use your judgement.
$var = "My $string with $lots of $replacements."
Is much more readable than:
$var = 'My ' . $string . ' with ' . $lots . ' of ' . $replacements . '.';
I'll admit that:
$var = "My string.";
Looks almost the same as:
$var = 'My String.';
However the latter introduces less noise and when there's lots of code around it every little bit helps, not to mention the other benefits you get from using single quotes.
In the end, I prefer to KISS. Use single quotes unless you need double quotes. Simple convention that is easier to type, easier to maintain, easier to parse and easier to read.
It doesn't matter from syntax perspective. Both variants are correct. Use what you feel more comfortable.
Personally, I feel better when using the $string="Hi, my name is $name", because you don't need to mess with quotes. Just image the complex SQL query with, let's say, 10 variables...
PHP is pretty slow:
http://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-088-introduction-to-c-memory-management-and-c-object-oriented-programming-january-iap-2010/lecture-notes/MIT6_088IAP10_lec01.pdf
Slide #3
So don't worry too much about little optimizations like these.
Focus more on using APC to cache your code into byte code though. You'll see big speed gains for the project.
Personally, if it's just a normal variable, or even a class property, I'd write it like this:
$newVarA = "This is some text with a $variable";
$newVarB = "This is some more text, written in $settings->language";
However, if I'm using array values then I'll concatenate with single quotes.
$newVarC = 'This is some text from a ' . $text['random'] . ' array';
Hope this makes sense. It's all about finding convention and sticking to it.
My motto and answer is: Leave it to the compilers to write machine code. I will tell you what I mean...
Use single quotes when you don't need to include PHP variables, otherwise use double quotes.
Dont bother about performance just use APC on production servers. Instead focus on writing the most maintainable code; use comments, double quotes etc. properly even though they may slow code down. Every optimization that decreases maintainability / readability of code is bad, leave it to the opcode-cachers and compilers to turn your code into machine code, don't do it yourself... obfuscating your source code because of optimization fires back.
The single quoted string is better option than double quoted string while concatenating the variables.
click the link for better understanding...
http://www.codeforest.net/php-myth-busters-using-single-quotes-on-string-is-faster-then-double-quotes
$string='Hi, my name is '.$name
This is the best way, in the sense of php and html combination!
or like this:
$string="Hi, my name is $name";
This is the old way!
Or like this:
$string=sprintf("Hi, my name is %s",$name);
This is what a programmer coming from Visual Basic or other Client Programming languages would write!
I hope I was helpful.
I'm attempting to wrap a user-inputted string in double quotes for output but I want to make sure I don't end up with double double quotes on either side of the string. For example, if a user posts
"Hello"
I don't want to turn it into
""Hello""
I can do this fairly easily using the code below, however I'm concerned that this may get slow if I'm looping through lots of strings.
$string = '"'.trim($string,'"').'"';
If anyone has a better way of doing this, that'd be great. Equally, if anybody can confirm that my way is fine, I'll be happy.
Thanks
This is exactly how I would solve this problem. It's only worth worrying about the code being slow if you have a problem with the application being slow, and you can trace it down to the trim statements.
A well known programming quote is "Premature Optimisation is the root of all evil" - see the wikipedia article linked for more on this.
Make a careful consideration of what should happen with all the cases.
(using [] as quotes for readability)
You've said what you do for ["Hello"] but what do you do for [I said "Hello", punk]? Do you still strip the user-input quotes, or do you remove them? Or maybe go one step further and substitute single quotes for double quotes...but then you'd have to consider the cases where the user input contains both single and double quotes! What about when the user puts in "grammatically wrong" text like ["Hello] (no closing quote!).
Best way to ensure you do it right is to make a test case for each edge case you can think of and make sure your proposed solution actually does what is expected.
If the actually reason for this requirement is [I am taking a user's input at some point and then re-displaying it to them at another point, and don't want to show them stupid looking data like [""data""]], you'll probably just want to only remove double quotes from the start or end of the input string, because stripping them from the middle screws with the user's intended data.
If your goal is merely to clearly distinguish between their input and text that they didn't input, consider using other means of highlighting that instead of quotation marks. So instead of [you entered "data"], you could display [you entered data] or [you entered: data] which avoid this problem altogether.
Personally, I'd suggest stripping the quotes on input. As for making it faster, if you allow quotes to be entered or stored, you're always going to be stuck with using an if/else before displaying them.
Obviously, you'd still need to perform a sanity check of the input data regardless of whatever system you end up with.
I did it this way:
function quotize(&$string)
{
if (empty($string) || is_null($string)) {
return;
}
$char = '"';
if ($string[0] != $char) {
$string = $char . $string;
}
if (substr($string, -1) != $char) {
$string .= $char;
}
return;
}
It is common practice to use quotation marks to represent a quote within a quote, if you want to let your users write:
and she said "hey ho"
, which you could turn into:
User: "and she said 'hey ho'"