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
.
Try this: str_replace('"', "", $string); str_replace("'", "", $string);
To remove double quotes just from the beginning and end of the String, we can use a more specific regular expression: String result = input. replaceAll("^\"|\"$", ""); After executing this example, occurrences of double quotes at the beginning or at end of the String will be replaced by empty strings.
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 );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With