How do I ensure attribute values containing quotes

2019-03-06 11:22发布

问题:

In my database I am storing the title of posts and when I create the links on the page I put the title of the post as the title attribute.

<a title='here is the description'>bluah</a>

But what is happening on the page is that in my descriptions there are characters that are breaking it. Example of a post title that breaks

<a title='I don't hanging out with friends, had a great time seeing Sarah again ;p '>bluah</a>

I think I need to do some HTML encoding, but I am not sure when/where I should be doing that.

Thanks

回答1:

Use htmlspecialchars to output your strings

htmlspecialchars("I don't",ENT_QUOTES); // returns I don&#039;t

That will also take care of other HTML characters such as < & > as explained in the manual,

http://php.net/manual/en/function.htmlentities.php