Mark
Mark

Reputation: 23

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.

Upvotes: 2

Views: 4290

Answers (3)

GG.
GG.

Reputation: 21864

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

Upvotes: 1

Orbling
Orbling

Reputation: 20612

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.

Upvotes: 7

Anomie
Anomie

Reputation: 94834

Use htmlentities or htmlspecialchars with the ENT_QUOTES flag to escape quotes in the text before outputting it.

Upvotes: 1

Related Questions