user1904273
user1904273

Reputation: 4764

php how to escape text in input textbox

I want to pre-populate an input textbox with text from a database. However, if the text from the database contains certain special characters such as a " mark, it interferes with the html and truncates everything after the quote mark.

Addslashes and also urlencode do not work because the textbox displays the asci text and you just see a slash mark before the quote mark or the encoded text ie %026.

Code:

<?php

//access data base
while $row=mysql_fetcharray($res) {

$dim =$row['dimension'];

}

echo 'Dimensions: <input type="text" size=20 name="dim" value="'.$dim.'">'; //truncates
echo 'Dimensions: <input type="text" size=20 name="dim" value="'.addslashes($dim).'">'; //shows slashes in textbox

         ?>

Would appreciate any solution to this vexing problem.

Upvotes: 0

Views: 2136

Answers (2)

user3030212
user3030212

Reputation: 439

Try this:

<?php
    $str = "Keep the 'quote'.";
    echo htmlentities($str, ENT_QUOTES, "UTF-8");
?>

Read more: htmlentities

Upvotes: 3

John Conde
John Conde

Reputation: 219884

What you're looking for is htmlspecialchars():

Certain characters have special significance in HTML, and should be represented by HTML entities if they are to preserve their meanings.

echo 'Dimensions: <input type="text" size=20 name="dim" value="'.htmlspecialchars($dim).'">';

Upvotes: 6

Related Questions