[英]How to remove single and double quotes from a string
當我通過此函數運行包含雙引號的短語時,它用quot替換引號。
我想完全刪除它們(也是單引號)。 我怎樣才能改變這個功能呢?
function string_sanitize($s) {
$result = preg_replace("/[^a-zA-Z0-9]+/", "", $s);
return $result;
}
更新:
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
我不會將該函數string_sanitize()
,因為它具有誤導性。 你可以稱之為strip_non_alphanumeric()
。
您當前的函數將刪除任何不是大寫或小寫字母或數字的內容。
您只需剝離'
和"
與...
$str = str_replace(array('\'', '"'), '', $str);
它看起來像你的原始字符串有HTML字符"
( "
所以當你試圖清理它,你只需刪除&
和;
,留下字符串的其余部分quot
。
- -編輯 - -
刪除非字母數字字符的最簡單方法可能是使用html_entity_decode解碼HTML字符,然后通過正則表達式運行它。 因為,在這種情況下,你不會得到任何東西,需要重新編碼,你不需要再做ヶ輛 ,但它是值得記住的是,你有 HTML數據,你現在有原始未經數據。
例如:
function string_sanitize($s) {
$result = preg_replace("/[^a-zA-Z0-9]+/", "", html_entity_decode($s, ENT_QUOTES));
return $result;
}
請注意, ENT_QUOTES
將函數標記為“...轉換雙引號和單引號”。
我認為你的preg_replace調用應該是這樣的:
$result = preg_replace("/[^a-zA-Z0-9]+/", "", html_entity_decode($s));
有關更多詳細信息,請參閱html_entity_decode參考 。
單引號和雙引號的簡單方法:)仍然留下類似於看的東西。
$clean_string = str_replace('"', '``', str_replace("'", "`", $UserInput));
為了確保刪除所有類型的引號(包括那些左側與右側不同的引號),我認為它必須是類似的;
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;
}
您的函數使用正則表達式刪除與[a-zA-Z0-9]不同的任何字符,因此它肯定會刪除任何“”或“”
編輯:好吧,從Hamish回答我發現你的字符串是一個HTML字符串,所以它解釋了為什么“(&”)被轉換為“quot”。你可以考慮用preg_replace替換"e
,或者首先考慮htmlspecialchars_decode 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.