31

I have an HTML form that a user can input text into a title field, I then have php creating an HTML file called title.html

My problem is that users can input spaces and apostrophes into the title field that can't be used in the html file name. I replaced the spaces with underscores by using:

$FileName = str_replace(" ", "_", $UserInput);

However, I can't seem to remove single-quotes? I have tried using:

$FileName = preg_replace("/'/", '', $UserInput); 

but this took test's and turned it into test\s.html.

1
  • 1
    You've got magic quotes turned on. This causes more problems than it solves, so turn them off.
    – staticsan
    Commented Oct 11, 2010 at 2:50

7 Answers 7

73

Using your current str_replace method:

$FileName = str_replace("'", "", $UserInput);

While it's hard to see, the first argument is a double quote followed by a single quote followed by a double quote. The second argument is two double quotes with nothing in between.

With str_replace, you could even have an array of strings you want to remove entirely:

$remove[] = "'";
$remove[] = '"';
$remove[] = "-"; // just as another example

$FileName = str_replace( $remove, "", $UserInput );
11

You can substitute in HTML entitiy:

$FileName = preg_replace("/'/", "\'", $UserInput);
4

You could also be more restrictive in removing disallowed characters. The following regex would remove all characters that are not letters, digits or underscores:

$FileName = preg_replace('/[^\w]/', '', $UserInput);

You might want to do this to ensure maximum compatibility for filenames across different operating systems.

1
$replace_str = array('"', "'", ",");
$FileName = str_replace($replace_str, "", $UserInput);
1
  • 1
    While this code snippet may solve the question, including an explanation really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. Please also try not to crowd your code with explanatory comments, this reduces the readability of both the code and the explanations! Commented Aug 22, 2016 at 20:47
1

Try this one. You can strip just ' and " with:

$FileName = str_replace(array('\'', '"'), '', $UserInput); 
0

I used this function htmlspecialchars for alt attributes in images

0
$test = "{'employees':[{'firstName':'John', 'lastName':'Doe'},{'firstName':'John', 'lastName':'Doe'}]}" ; 
$test = str_replace("'", '"', $test);
echo   $test;
$jtest = json_decode($test,true);
var_dump($jtest);

Not the answer you're looking for? Browse other questions tagged or ask your own question.