Mark Mark - 5 months ago 27
PHP Question

Adding PHP string variable to textbox value that includes quotation marks

I'm trying to populate an HTML text box with a php variable. The variable is a string with a single quotation mark in it and is retrieved from a database.

When I echo the variable it looks as it's supposed to - ie. "here's my string" so, it's correctly displaying the ' single quotation mark.

But when I try to put that variable into a text box field ie.

<? echo("<input type='text' name = 'title' value='$title'/>");?>

The quotation mark is ignored..

Any help is greatly appreciated as I've tried running the variable through a number of HTML formatting functions but to no avail.


You should change it to this:

<input type="text" name="title" value="<?php echo htmlentities($title, ENT_QUOTES); ?>" />

htmlspecialchars() and htmlentities() are used to convert strings in to HTML with correct encoding.

The ENT_QUOTES option ensures that the apostrophes and speech marks are also correctly encoded.