Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing single-quote from a string in php

Tags:

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.

like image 671
micahmills Avatar asked Oct 11 '10 02:10

micahmills


People also ask

How remove single quotes and double quotes from string in PHP?

Try this: str_replace('"', "", $string); str_replace("'", "", $string);

How do you remove quotation marks from a 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.


1 Answers

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 ); 
like image 110
hookedonwinter Avatar answered Oct 04 '22 13:10

hookedonwinter