Handling apostrophes when generating HTML with PHP

前端 未结 5 751
慢半拍i
慢半拍i 2020-12-22 02:13

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

相关标签:
5条回答
  • 2020-12-22 02:48

    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.

    0 讨论(0)
  • 2020-12-22 02:54

    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.

    0 讨论(0)
  • 2020-12-22 02:57

    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

    0 讨论(0)
  • 2020-12-22 02:59

    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 讨论(0)
  • 2020-12-22 03:05

    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\".";

    0 讨论(0)
提交回复
热议问题