我試圖寫一個正則表達式,允許單個連字符和單個空格只在單詞內但不在單詞的開頭或結尾。PHP的preg_match與正則表達式:只有單個連字符和單詞之間的空格繼續
,我想我有這個從answer昨天我排序,但我才意識到有小錯誤,我也不太明白,
爲什麼它不會接受像輸入,
'forum-category-b forum-category-a'
'forum-category-b Counter-terrorism'
'forum-category-a Preventing'
'forum-category-a Preventing Violent'
'forum-category-a International-Research-and-Publications'
'International-Research-and-Publications forum-category-b forum-category-a'
但需要,
'forum-category-b'
'Counter-terrorism forum-category-a'
'Preventing forum-category-a'
'Preventing Violent forum-category-a'
'International-Research-and-Publications forum-category-b'
這是爲什麼?我該如何解決它?它下面是與初始試驗中的正則表達式,但理想地應該接受上述所有的組合輸入,
$aWords = array(
'a',
'---stack---over---flow---',
' stack over flow',
'stack-over-flow',
'stack over flow',
'stacoverflow'
);
foreach($aWords as $sWord) {
if (preg_match('/^(\w+([\s-]\w+)?)+$/', $sWord)) {
echo 'pass: ' . $sWord . "\n";
} else {
echo 'fail: ' . $sWord . "\n";
}
}
接受/拒絕輸入等這些下面,
---stack---over---flow---
stack-over-flow- stack-over-flow2
stack over flow
感謝。
您可能想了解Dash標點符號的'\ p {Pd}'屬性。 – tchrist