micahmills micahmills - 1 year ago 201
PHP Question

Removing single-quote from a string in php

I have an HTML form that a user can input text into a

field, I then have php creating an HTML file called

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
and turned it into

Answer Source

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 );
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download