PHP preg_Match with Regular Expression:单词之间只有单个连字符和空格 [英] PHP preg_match with regular expression: only single hyphens and spaces between words

查看:28
本文介绍了PHP preg_Match with Regular Expression:单词之间只有单个连字符和空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

这篇关于PHP preg_Match with Regular Expression:单词之间只有单个连字符和空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆