Regular expression filter string regular expression PHP
Reply to discussion (solution)
$ Str = "new _ Build & file \, folder abd"; echo preg_replace ('/[_ & \\\, \ s] +/U ','', $ str );
// The Chinese encoding contains the UTF-8, GBK $ str = "new _ Build & file \, folder abd"; // get the result $ res = "new folder abd "; // contains invalid characters: $ out [0] = "_"; $ out [1] = "&"; $ out [2] = "\\"; $ out [3] = ""; $ out [4] = ","; $ pattern = join ('|', array_map ('preg _ quote ', $ out); echo preg_replace ("/$ pattern/", '', $ str );
Create a folder named abd
Right? The orangutan also asked this question?
#1, #2 is feasible, but the solution does not cure the problem;
I didn't make it clear. in this way, $ out is the character that is filtered out. I didn't know it before. I just gave an example of these illegal characters.
Actual goal: after obtaining the input form result, deduct all illegal characters except Chinese characters and English letters.
If the English letters are good to determine the range, meet the requirements of the [A-Za-z0-9], that is, all other illegal characters.
However, if you add a mix of Chinese and English characters, unless you determine the range of all Chinese characters, there is no good way to deduct it, for example, GBK can usually use [\ x80-\ xff] [\ x40-\ xfe] to indicate the range of Chinese characters. Note that this is only the approximate range. if it is utf8, it is \ u4e00-\ u9fa5. if there are some characters that you think are illegal, there is no way to kill them.
Roughly speaking, the range of all illegal characters other than Chinese and English letters in gbk should be [^ A-Za-z0-9 \ x80-\ xff \ x40-\ xfe]
Utf8 is [^ A-Za-z0-9 \ x {4e00}-\ x {9fff}]
Echo preg_replace ('/[^ A-Za-z \ p {Han}] +/U', ''," _ & 文\ \, abd ");
The above gbk regular expression is wrong. you can see it in the example.
If it is gbk, you can use the following method
$ Test = 'new_document, folder [? [Abd '; $ out = preg_split ('/([a-zA-Z0-9] | [\ x80-\ xff].) +/', $ test); $ matches = array (); preg_match_all ('/([a-zA-Z0-9] | [\ x80-\ xff].) /', $ test, $ matches); $ res = implode ($ matches [1]); var_dump ($ res ); $ out = str_split (str_replace ($ matches [1], '', $ test); var_dump ($ out );
#5 no results...
OK, #6 can be used. Thank you for your support.
#5 no results...
To use utf8 matching rules, add the u pattern match after the regular expression, that is
Echo preg_replace ("/[^ A-Za-z0-9 \ x {4e00}-\ x {9fff}]/u", '', $ str );
In fact, \ p {Han} is equivalent to \ x {4e00}-\ x {9fff} in some sense}