簡體   English   中英

在PHP中刪除任何字符,但不刪除符號和字母

[英]remove in php any character but not symbols and letters

我如何使用str_ireplace或其他函數刪除任何字符,但不刪除HTML中常用的字母,數字或符號: " ' ; : . - + = ...等我還想刪除/ n,空格,標簽和其他。

我需要那個文本,來自做(“textContent”)。 IE10和Chrome中的innerHTML,php變量大小相同,無論哪個瀏覽器都這樣做。因此我需要在兩個文本中使用相同的編碼,並刪除罕見或不同的字符。

我試試這個,但它不適合我:

        $textForMatch=iconv(mb_detect_encoding($text, mb_detect_order(), true), "UTF-8", $text);
        $textoForMatc = str_replace(array('\s', "\n", "\t", "\r"), '', $textoForMatch);

$ text包含函數的結果(“textContent”)。 innerHTML,我想刪除字符為 ó³..

最簡單的選擇是簡單地將preg_replace與白名單一起使用。 即使用列出您要保留的內容的模式,並替換不在該列表中的任何內容:

$input = 'The quick brown 123 fox said "�é³". Man was I surprised';
$stripped = preg_replace('/[^-\w:";:+=\.\']/', '', $input);
$output = 'Thequickbrownfoxsaid"".ManwasIsurprised';

正則表達式的解釋

/       - start regex
[^      - Begin inverted character class, match NON-matching characters
-       - litteral character
\w      - Match word characters. Equivalent to A-Za-z0-9_
:";:+=  - litteral characters
\.      - escaped period (because a dot has meaning in a regex)
\'      - escaped quote (because the string is in single quotes)
]       - end character class
/       - end of regex

因此,這將刪除正則表達式中列出的任何非單詞,數字或特定字符的內容。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM