$tests[1] = "fail_.fail"; // doubles
$tests[] = "fail_-fail";
$tests[] = "fail_ fail";
$tests[] = "fail fail";
$tests[] = "fail -fail";
$tests[] = "pas.s_1";
$tests[] = "pa.s-s_2"; // singles
$tests[] = "pas.s_3";
$tests[] = "p.a.s.s_4";
$tests[10] = "pa s-s_5";
$tests[] = "fail fail'"; // pre or post-pended
$tests[] = " fail fail";
$tests[] = " fail fail";
$tests[] = "fail fail_";
$tests[15] = "fail fail-";
// The list of disallowed characters. There is no need to escape.
// This will be done with the function preg_quote.
$exclude = array(" ","'", "_", ".", "-");
$pattern = "#[" . preg_quote(join("", $exclude)) . "]{2,}#s";
// run through the simple test cases
foreach($tests as $k=>$test){
if(
in_array(substr($test, 0, 1), $exclude)
|| in_array(substr(strrev($test), 0 , 1) , $exclude))
{
echo "$k thats a fail" . PHP_EOL;
continue;
}
$test = preg_match($pattern, $test);
if($test === 1){
echo "$k - thats a fail". PHP_EOL ;
}else{
echo "$k - thats a pass $test ". PHP_EOL ;
}
}
從對方回覆絕望偷,我提倡用PHP的簡單in_array檢查首先開始和結束字符串,並在發現不好的事情時提前失敗。
如果測試過去了,那麼運行一個非常簡單的正則表達式。
將這個區域粘貼到一個函數中,並在失敗時返回false - 這可能是我添加的相當多的冗長行 - 您甚至可以將排除數組作爲變量發送 - 但它看起來相當具體的功能所以可能是YAGNI
如
if(badString($exclude_array, $input)) // do stuff
你想修理,更換並進行..或在發現故障時,只需放棄? – Cups 2013-02-20 10:21:32
發現錯誤,並去轟隆隆:)謝謝杯子 – Tim 2013-02-20 10:28:49
關於這句話:*也阻止任何兩個這樣的字符在一行,即''或_._或'-__-'。*好,所以沒有一個單一的apostrophs在一排但是對於其他情況('_._'和''-__-'.'),你的意思是什麼? – kjetilh 2013-02-20 10:34:15