带有正则表达式的PHP preg_match:单词之间只有单个连字符和空格

时间:2011-02-08 00:48:36

标签: php regex preg-match space

如何只在单词内允许单个连字符和单个空格,而不是在单词的开头或结尾处?

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

感谢。

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

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

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

参考: preg_replacetrim

答案 2 :(得分:1)

接受其间有空格的字符或数字。如果只是空间,它不通过测试或不接受。

此正则表达式接受“家庭作业”之类的字符串,但失败并带有“”。

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

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