PHP preg_Match with Regular Expression:单词之间只有单个连字符和空格

2022-03-29 00:00:00 regex space php preg-match

如何只允许在单词内使用单连字符和单空格,而不允许在单词的开头或末尾使用?

if(!preg_match('/^[a-zA-Z0-9-s]+$/', $pg_tag))
    {
        $error = true;
        echo '<error elementid="pg_tag" message="TAGS - only alphanumbers and hyphens are allowed."/>';
    }

我不想接受下面的这些输入

---stack---over---flow---
stack-over-flow- stack-over-flow2
   stack    over    flow

但只有这些才是可接受的

stack-over-flow stack-over-flow2 stack-over-flow3
stack over flow
stacoverflow

谢谢。


解决方案

$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 . "
";
    } else {
        echo 'fail: ' . $sWord . "
";
    }
}

和输出:

pass: a
fail: ---stack---over---flow---
fail:    stack    over    flow
pass: stack-over-flow
pass: stack over flow
pass: stacoverflow

Regex明细:

^             # 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

相关文章