开发者

finding if string is already escaped or not?

开发者 https://www.devze.com 2023-03-29 09:58 出处:网络
I am getting following data <font color=\\\"#ff0000\\\" face=\\\"Verdana\\\" size=\\\"5\\\">hello there</font><br/>

I am getting following data

<font color=\"#ff0000\" face=\"Verdana\" size=\"5\">hello there</font><br/>

I have 2 questions

  • How can I find whether quotes and other things are already escaped (i.e., already preceeded开发者_高级运维 by \ or not)?

  • I will be storing this string to one of the fields in database table. Should I convert all HTML special characters to entities like < should be converted to &lt


For storing the data into a database, you don't need to convert the HTML entities. You just need to escape the characters that have special meaning in MySQL, using mysql_real_escape_string() in PHP for instance. An even better method is using a library like PDO and prepared statements (this will take care of escaping the variables for you).

For displaying the HTML data (unescaped), you can use a function like stripslashes to remove the slashes. On a sidenote: how come you don't know if the string is escaped or not? If it comes from another section of your application, you should know.


Maybe it is best to be safe than sorry and just use stripslashes to remove any slash that could be present.


a. I think this regex will do the job:

[^\\]["]

This regex will be true if there is any " that's not escaped. You can add as many characters as you want to the second set (["]) to make sure they're escaped.


  • You can strip slashes and add them again
  • You need not to encode entities to store them in DataBase.
    You need it only if you will print it in HTML as literraly string (not as tags) (i.e you want to see < char)


At some later point you want this HTML to be used to build a webpage, right? Both escaping the quotes and replacing the HTML special characters with entities will only give you additional work then. So my suggestion is to use parametrized query to avoid the "is the quotes escaped" problem and not to replace the special characters.


You can do it with:

$a=addslashes(stripslashes($a));

then both slashed or unslashed "/' would be slashed.

0

精彩评论

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