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
How remove single quotes and double quotes from string in PHP? Use str. strip(chars) on str with the quote character '"' as chars to remove quotes from the ends of the string.
Since you're using single quotes to create our string, you can include double quotes within it to be part of the final string that PHP outputs. If you want to render the \' sequence, you must use three backslashes ( \\\' ). First \\ to render the backslash itself, and then \' to render the apostrophe( ' ).
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);
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