How to remove single and double quotes from a string

When I run a phrase that contains double quotes through this function, quot quotes replace it.

I want to remove them completely (also single quotes). How can I change the function for this?

function string_sanitize($s) { $result = preg_replace("/[^a-zA-Z0-9]+/", "", $s); return $result; } 

Update:

 Example 1: This is 'the' first example returns: Thisis030the039firstexample Errors: Warning: preg_match_all() [function.preg-match-all]: Unknown modifier '0' in C Example 2: This is my "second" example returns: Thisismyquotsecondquotexample Errors: Invalid express in Xpath 
+8
php preg-replace
source share
5 answers

It looks like your original string had HTML characters for " ( " ), so when you try to sanitize it, you simply delete & and;, leaving the rest of the quot string.

--- EDIT ---

Probably the easiest way to remove non-abedic numeric characters would be to decode the HTML characters with html_entity_decode and then run it through a regular expression. Since in this case you will not get anything that needs to be transcoded, you do not need to do htmlentities , but it is worth remembering that you have HTML data and now you have unprocessed unencoded data.

For example:

 function string_sanitize($s) { $result = preg_replace("/[^a-zA-Z0-9]+/", "", html_entity_decode($s, ENT_QUOTES)); return $result; } 

Note that ENT_QUOTES denotes the function "... convert both double and single quotes."

+12
source share

I would not call this function string_sanitize() , as it is misleading. You can call it strip_non_alphanumeric() .

Your current function will split everything that is not a string or a string.

You can only divide ' and " into ...

 $str = str_replace(array('\'', '"'), '', $str); 
+24
source share

I think your preg_replace call should look like this:

 $result = preg_replace("/[^a-zA-Z0-9]+/", "", html_entity_decode($s)); 

See the html_entity_decode reference for more details.

+1
source share

Your function uses a regular expression to remove any character other than [a-zA-Z0-9], so it will certainly remove any "or"

EDIT: well, from Hamish's answer, I understand that your string is an HTML string, so it explains why "(& quot) is converted to" quot. "You might consider replacing "e with preg_replace or htmlspecialchars_decode .

0
source share

To exclude all quotation marks (including those in which the left side is different from the right), I think it should be something like:

 function string_sanitize($s) { $result = htmlentities($s); $result = preg_replace('/^(")(.*)(")$/', "$2", $result); $result = preg_replace('/^(«)(.*)(»)$/', "$2", $result); $result = preg_replace('/^(“)(.*)(”)$/', "$2", $result); $result = preg_replace('/^(')(.*)(')$/', "$2", $result); $result = html_entity_decode($result); return $result; } 
0
source share

All Articles