Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
348 views
in Technique[技术] by (71.8m points)

php - Single and double quotes together as HTML attribute value?

We have a code like this:

echo '<input type="text" name="myInput" value="Double " Quotes" />';

Absolutely it doesn't work because the quote after Double ends the value. We can fix it by using single quotes instead of double ones.

echo '<input type="text" name="myInput" value='Double " Quotes' />';

Now I wanna use both single and double quotes as the value. It should outputs She said:"I don't know."

Is there a way to fix it WITHOUT using HTML entities (Like &quot;), htmlentities() or similar functions?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Is there a way to fix it WITHOUT using HTML entities (Like &quot;), htmlentities() or similar functions?

No, there is not. The double quote (") has special meaning inside a HTML attribute. If you want to put it into an attribute value, you must (this is not a true must but a good rule of thumb. It's a must if you use attributes delimited by double-quotes as you do in your question) write it as its entity &quot;. There is no way around it.

Actually even <tag attr='this"'> is not wrong HTML, too and most browsers can deal with that. However it doesn't help you because you're looking for both quotes - single and double - and one of these always in HTML is a delimiter of the attribute value - if you need spaces inside the attribute value (as you do).

However, do not worry about that. It works, and you can express everything you like with that, including the combination of quotes you have.

And actually PHP is there for you to take the burden of "escaping" all those characters just with the htmlspecialchars method doing all the work for you. Inside a PHP string you have the original text - with single and double quotes as you see fit - verbatim.

$myString = 'She said: "I don't know."';
printf('<input type="text" name="myInput" value="%s" />'
       , htmlspecialchars($myString));

Just a shortened example that should demonstrate how this works. Online demo.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...