Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I strip quotes from an input box using PHP

I have this:

<input name="title" type="text" class="inputMedium" value="' . $inputData['title'] . '" />

I want to strip quotes from user input so that if someone enters something like: "This is my title" it wont mess up my code.

I tried this and it's not working:

$inputData['title'] = str_replace('"', '', $_POST['title']);
like image 387
Babak Avatar asked Feb 17 '10 20:02

Babak


People also ask

How do I strip a quote in PHP?

Try this: str_replace('"', "", $string); str_replace("'", "", $string); Otherwise, go for some regex, this will work for html quotes for example: preg_replace("/<!

How do you strip a quote from a string?

To remove double quotes from a string:Call the replace() method on the string. The replace method will replace each occurrence of a double quote with an empty string. The replace method will return a new string with all double quotes removed.


1 Answers

If I understand the question correctly, you want to remove " from $inputData['title'], so your HTML code is not messed up?

If so, the "right" solution is not to remove double-quotes, but to escape them before doing the actual output.


Considering you are generating HTML, **you should use the [`htmlspecialchars`][1] function**; this way, double-quotes *(and a couple of other characters)* will be encoded to HTML entities, and will not cause any trouble when injected into your HTML markup.

For instance:

echo '<input name="title" type="text" class="inputMedium" value="'
   . htmlspecialchars($inputData['title'])
   . '" />';

Note: depending on your situation (especially, about the encoding/charset you might be using), you might to pass some additional parameters to htmlspecialchars.

Generally speaking, you should always escape the data you are sending as an output, not matter what kind of output format you have.

For instance:

  • If you are generating some XML or HTML, you should use htmlspecialchars
  • If you are generating some SQL, you should use mysql_real_escape_string, or an equivalent, depending on the type of database you're working with
like image 75
Pascal MARTIN Avatar answered Oct 20 '22 00:10

Pascal MARTIN