Reputation: 888
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
.
Upvotes: 32
Views: 125682
Reputation: 4765
Try this one. You can strip just '
and "
with:
$FileName = str_replace(array('\'', '"'), '', $UserInput);
Upvotes: 1
Reputation: 113
$replace_str = array('"', "'", ",");
$FileName = str_replace($replace_str, "", $UserInput);
Upvotes: 1
Reputation: 2114
$test = "{'employees':[{'firstName':'John', 'lastName':'Doe'},{'firstName':'John', 'lastName':'Doe'}]}" ;
$test = str_replace("'", '"', $test);
echo $test;
$jtest = json_decode($test,true);
var_dump($jtest);
Upvotes: 0
Reputation: 316
I used this function htmlspecialchars for alt attributes in images
Upvotes: 0
Reputation: 185861
You can substitute in HTML entitiy:
$FileName = preg_replace("/'/", "\'", $UserInput);
Upvotes: 11
Reputation: 2669
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.
Upvotes: 4
Reputation: 12666
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 );
Upvotes: 73