Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove apostrophe from a string using php

Tags:

php

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
like image 722
Xylon Avatar asked Aug 12 '14 04:08

Xylon


People also ask

How to remove single quote in PHP?

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.

How to add apostrophe in PHP?

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( ' ).


2 Answers

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.

like image 178
Devon Avatar answered Oct 05 '22 20:10

Devon


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);
like image 23
GLaming Avatar answered Oct 05 '22 19:10

GLaming