Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use str_replace to replace single and double quotes

Tags:

php

I have to create a login in form which a user will insert a username and a password. I have to ensure that html entities are not processed, and I can not allow single quotes or double quotes to be processed either. I must echo the data entered into the form and display it.

I must use htmlentities and str_replace. I have the htmlentities correct, but am unsure on how to utilize the str_replace function to replace the single and double quotes that the user might enter into the form. Any help would be awesome.

Here is my current PHP (which works)

<?php
$username = htmlspecialchars($_POST['username']);
$password    = htmlspecialchars($_POST['password']);
$comment = htmlspecialchars($_POST['comment']);
?>
<html>
<body>
Your username is: <?php echo $username; ?><br />
Your password: <?php echo $password; ?><br />
Your Comment was: <?php echo $comment; ?>

like image 748
Jeremy Flaugher Avatar asked Feb 07 '13 04:02

Jeremy Flaugher


4 Answers

First of all, it is always better to check for the unwanted characters and get back to the user, than silently stripping them. Say, a user added a quote to their password, you removed it, and so they won't be able to login at all! So it's better to check and tell the user instead:

if (!ctype_alnum($username)) { 
    $errors[] = "Only letters and numbers allowed in username";
}
...
if ($errors) {
    echo "You've got some errors, please fix them: ". implode("<br>", $errors);
} else {
    // proceed with normal flow

But in this specific case I would advise against replacing any characters. Imagine Shaquille "Shaq" O'Neal is going to register on your site. What's the point in stripping him of all those quotes? Let alone the password, where use of punctuation is strongly encouraged.

After all, those quotes don't do any harm, if you properly handle them.

  • for HTML, simply use htmlspecialchars() with ENT_QUOTES attribute:

      Your username is: <?= htmlspecialchars($username, ENT_QUOTES) ?><br />
    
  • for SQL, use prepared statements to avoid any problems with quotes

But just for sake of literal answer, here is how to remove quotes (or any other characters and even multi-character substrings) in PHP

$yourVariable = "scor\"pi'on";
$substringsToRemove = ['\'', '"'];
$yourVariable = str_replace($substringsToRemove, "", $yourVariable);
like image 194
ScoRpion Avatar answered Oct 20 '22 00:10

ScoRpion


 $keyItem = str_replace ("'","\'",$keyItem);

This replaces a single quote with an 'escaped' single quote \' .

like image 41
user462990 Avatar answered Oct 20 '22 00:10

user462990


$username = htmlentities(str_replace(array('"', "'"), '', $_POST['username']));
like image 36
Barmar Avatar answered Oct 20 '22 00:10

Barmar


$username = str_replace(array("'", "\""), "", htmlspecialchars($_POST['username']));
like image 40
Samuel Liew Avatar answered Oct 20 '22 01:10

Samuel Liew