Is there a anyway to remove apostrophe from a string in php? example:- If string is Mc'win then it should be shown as Mcwin
$Str = "Mc'win";
/*
some code to remove the apostrophe
*/
echo $Str; // should display Mcwin
Is there a anyway to remove apostrophe from a string in php? example:- If string is Mc'win then it should be shown as Mcwin
$Str = "Mc'win";
/*
some code to remove the apostrophe
*/
echo $Str; // should display Mcwin
You can use str_replace.
$Str = str_replace('\'', '', $Str);
or
$Str = str_replace("'", '', $Str);
This will replace all apostrophes with nothing (the 2nd argument) from $Str
. The first example escapes the apostrophe so str_replace will recognize it as the character to replace and not part of the enclosure.
If your variable has been sanitized, you may be frustrated to find you can't remove the apostrophe using $string = str_replace("'","",$string);
$string = "A'bcde";
$string = filter_var($string, FILTER_SANITIZE_STRING);
echo $string." = string after sanitizing (looks the same as origin)<br>";
$string = str_replace("'","",$string);
echo $string." ... that's odd, still has the apostrophe!<br>";
This is because sanitizing converts the apostrophe to '
, but you may not notice this, because if you echo the string it looks the same as the origin string.
You need to modify your replace search characters to '
which works after sanitizing.
$string = str_replace("'","",$string);
in my case, i got single quote issue when i wanted to store it to database (in my case MySQL). So, i remove the single quotes using this method
str_replace("'", "", trim($_GET["message"]))
But, the problems comes. Some data required us to have single quotes. So, instead of removing the quotes I try to save the single quotes (escaping single quotes) so it can be used in the future (in my case at Android)
My Idea is to replace from '
to ''
.
So here is the final
$content = str_replace("'", "''", trim($_GET["message"])); // double quotes for escape single quotes
This answer is for someone that persist problem like me. I got better solution. Cheers!