Thursday, March 28, 2013

Too many quotes

KNOW:
php, Javascript

Ever came across this problem?

echo ('<input id='fred' ...etc)

The problem is that we have an embedded quote but you say -- no problem right?

echo ("<input id='fred' ...etc)

So far so good.  Here we have the id of the tag set to 'fred'.  We use single quotes for fred and double quotes for input...but!


echo ("<input id='fred' onclick='DoSomething ('Bob');'...mess!

The problem is that you only have two normal layers of quotes.  The single can be embedded in the double but the double...we don't have a triple.  What we do have is the escape.

The escape lets us embed as many quotes as we want with the use of the \ character.

\" means to tell the processor that we want a double quote as it.  So when PHP processes the code we will see a double quote.  This won't work for single quotes by the way.  Don't do \' and expect good things to happen.

Now...

echo (\"<input id=\"fred\" onclick=\"DoSomething (\"Bob\")\" >\" );

I agree, this takes a bit of getting used to but the advantage is that you don't have to deal with running out of characters for quotes.  It works this way.

The first quote is always \"
The second quote is always \"
The third quote is always \"

You can do as many as you want without pulling hairs.  Messy -- ya...but it works.

No comments:

Post a Comment