开发者

Handling apostrophes when generating HTML with PHP

I am generating radio buttons based on an XML config values. Sometimes they have apostrophes in the text. When manipulating this data in PHP, I seem to lose everything after the apostrophe. For example:

<input type='radio' name='remove[]' value='Government wants to limit employers' communications about uni开发者_开发技巧onization'>

But when dumping it out after the form POSTs, I get this value:

array(1) {
[0]=>
string(35) "Government wants to limit employers"
}

Any suggestions on how to preserve the full string? Thanks!


use htmlspecialchars():

<input type="radio" ... value="<?php echo htmlspecialchars($array[0], ENT_QUOTES) ?>" ... />

It's explicitly intended to allow safe insertion of arbitrary text into html without 'breaking' the html. Note the 'ent_quotes' option. By default htmlspecialchars will only handle <>", but since you're using ', you need the option to tell htmlspecialchars to handle those too.


You can escape the quotes in the string: value='Government wants to limit employers&#39; communications about unionization' Escaping it will cause this problem to stop.

PHP does give functions for this, in case your information is in a variable. Just use htmlspecialchars


Simplest way would be just to use double quotes like so:

<input type='radio' name='remove[]' value="Government wants to limit employers' communications about unionization">

It's pretty much the reason for them.


I usually stick with those 2 easy options, both equally efficient:

  1. You can encapsulate one type of quotes in the other type

$var = " here single quotes ' are encapsulated in double quotes";
$var = 'here double quotes " are encapsulated in single quotes';

  1. you can escape quotes by using \

$var = "just quote some mathematician: \"quot erat demonstrandum\".";


You can use double quotes to surround the text:

<input type='radio' name='remove[]' value="Government wants to limit employers' communications about unionization">

An even better way would be to replace the apostrophes with &#39;.

<input type='radio' name='remove[]' value='Government wants to limit employers&quot; communications about unionization'>

This is a more robust solution in case the text includes double quotes as well. You should replace all 's with &#39;s and "s with &quot;s.

This can be easily done using htmlspecialchars(string $str). http://php.net/manual/en/function.htmlspecialchars.php

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜