2016-09-29 91 views
1

我有以下的正則表達式:在URL淨化的正則表達式中包含反斜槓?

$url = "http://example.com?param=test1\test2\test3\test4"; 

$cleanUrl = preg_replace('|[^a-z0-9-~+_.?\[\]\^#=!&;,/:%@$\|*`\'<>"()\\x80-\\xff\{\}]|i', '', $url); 

我得到以下輸出:

http://example.com?param=test1est2est3est4

但是, 我期待下面的輸出:

http://example.com?param=test1 \ TEST2 \ TEST3 \ TEST4

我想這正則表達式,但它不工作:

$cleanUrl = preg_replace('|[^a-z0-9-~+_.?\[\]\^\\#=!&;,/:%@$\|*`\'<>"()\\x80-\\xff\{\}]|i', '', $url); 
                ^escaped single quote 
+0

你確定輸入字符串?請參閱https://ideone.com/OnepGA。我認爲它應該是'$ url =「http://example.com?param=test1\\test2\\test3\\test4」;'。然後使用'$ cleanUrl = preg_replace('| [^ - \\\\ a-z0-9〜+ _。?\ [\] \ ^#=!&;,/:%@ $ \ | * \' '<>「()\ x80- \ xff \ {\}] | i','',$ url);'。請參閱[此演示](https://ideone.com/tUHtU3)。 –

+0

您必須使用\\\\來轉義反斜線。閱讀此[SO答案](http://stackoverflow.com/a/4025505/5447994) – Thamilan

回答

1

也許,你在做什麼,可以用其他方式來實現,但回答你的問題,我應該注意,您的輸入字符串不包含反斜槓,它包含選項卡字符作爲雙引號字符串文字內部,\t定義轉義序列。

一旦您使用單引號文字,\t表示2個符號。現在,正則表達式沒有\。你需要與\\\\添加:

$url = 'http://example.com?param=test1\test2\test3\test4'; 
$cleanUrl = preg_replace('|[^-\\\\a-z0-9~+_.?\[\]^#=!&;,/:%@$\|*`\'<>"()\x80-\xff{}]|i', '', $url); 
echo $cleanUrl; 

this PHP demo打印http://example.com?param=test1\test2\test3\test4

我也將-移到開頭(如果它應該與文字連字符匹配,最好將它放在字符類的開始或結尾處),並且^不在初始位置char類不一定要被轉義。 {,}[也是一樣,但是方括號更好地逃脫了(一些正則表達式禁止在字符類中使用未轉義的[)。

相關問題