[php] Removing single-quote from a string in php

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.

This question is related to php

The answer is


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

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

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

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

I used this function htmlspecialchars for alt attributes in images


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.


You can substitute in HTML entitiy:

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