【发布时间】:2011-02-08 23:29:59
【问题描述】:
我正在尝试编写一个正则表达式,它只允许在单词中使用单个连字符和单个空格,而不是在单词的开头或结尾。
我以为我是从昨天收到的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
谢谢。
【问题讨论】:
-
您可能想了解破折号标点符号的
\p{Pd}属性。
标签: php regex preg-match