1

我怎样才能只在单词中允许单个连字符和单个空格,而不是在单词的开头或结尾?

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

谢谢。

4

3 回答 3

5
$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
于 2011-02-08T00:57:03.380 回答
1

关于评论:另一个想法是“规范化”输入,即将所有连续的空格和破折号减少为一个并将它们从开头和结尾删除:

$pg_tag = preg_replace(array('/\s+/', '/-+/'), 
                       array(' ', '-'), 
                       trim($pg_tag, ' -'));

参考: preg_replace ,trim

于 2011-02-08T00:59:32.240 回答
1

接受中间有空格的字符或数字。在只有空间的情况下,它无法通过测试或仅不接受。

此正则表达式接受类似“Home Work”的字符串,但以“”失败。

var pattern = /^(?=.*\S)[.+a-z0-9A-Z-.#:!*$^_|?` ]+$/;
     return pattern.test(value);

如果接受字符串,则返回 true。

于 2014-10-28T14:08:30.893 回答