$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";
}
}
А на выходе:
pass: a
fail: ---stack---over---flow---
fail: stack over flow
pass: stack-over-flow
pass: stack over flow
pass: stacoverflow
Распределение регулярных выражений:
^ # Match from the very beginning of the string
( # Start Group
\w+ # At least one "word" character
( # Start Subgroup
[\s-] # A single space or a dash
\w+ # At least one "word" character
)? # End Subgroup is optional
)+ # End group - allow it multiple times
$ # Match until the very end of the string