12

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
Xylon
  • 461
  • 4
  • 11
  • 20
  • @Ghost I've used str_replace.. but didn't know how to replace a character with nothing... BTW thanx :) – Xylon Aug 12 '14 at 04:51

3 Answers3

19

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.

Devon Bessemer
  • 34,461
  • 9
  • 69
  • 95
7

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 &#39; , 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 &#39; which works after sanitizing.

$string = str_replace("&#39;","",$string);
GLaming
  • 87
  • 2
  • 8
  • Your response helped with my frustration. I did however need to amend your replace to; $string = str_replace("'","",$string); – Ben May 27 '20 at 11:39
0

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!

Yohanim
  • 3,319
  • 9
  • 52
  • 92
  • In modern programming, you should be manually escaping quotes, but using prepared statements when interacting with your database. – mickmackusa Jan 25 '23 at 03:36