2011-03-28 29 views
8

當我運行,通過該功能,它與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 
+0

此功能已經削減了兩個'''和'「' – zerkms 2011-03-28 03:14:53

回答

12

它看起來像你的原始字符串有HTML字符""),所以當你試圖清理它,你只需刪除&;,留下字符串quot的其餘部分。

---編輯---

大概除去非字母數字字符是將HTML字符html_entity_decode進行解碼,然後通過正則表達式運行它的最簡單的方法。因爲在這種情況下,您不會得到需要重新編碼的任何內容,因此您不需要再執行htmlentities,但值得記住的是,您的的HTML數據,而您現在有未編碼的原始數據。

如:

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

注意ENT_QUOTES標誌的功能 「......都轉換雙人和單引號。」

+0

哦。好猜測。 – 2011-03-28 03:23:18

+0

+1大點和觀察。任何想法我怎麼能剝奪"e;呢? – 2011-03-28 03:26:12

+0

用你如何做的例子編輯。 – Hamish 2011-03-28 03:32:31

0

你的函數使用正則表達式,以消除任何字符,從[A-ZA-Z0-9]不同的,所以它一定刪除任何「」或「」

編輯:好了,從麥答案,我意識到你字符串是一個HTML字符串,所以它解釋了爲什麼「(& QUOT)被轉化爲‘QUOT’。你可以考慮更換通過了preg_replace &quote,或htmlspecialchars_decode第一。

24

我不會調用該函數string_sanitize(),因爲它是一種誤導。你可以把它strip_non_alphanumeric()

您目前的功能將去除任何不是大寫或小寫字母或數字的東西。

可以大道僅有'"與...

$str = str_replace(array('\'', '"'), '', $str); 
+0

簡單而好的解決方案 – Praveen 2017-05-02 09:04:33

1

我覺得你的preg_replace調用應該是這樣的:

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

請參閱html_entity_decode reference瞭解更多詳情。

0

爲了確保刪除所有種類的報價(包括在其中左側是從右側的人不同),我想那一定是這樣的;

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; 
}