PHP preg_match with regular expression: only single hyphens and spaces between words(PHP preg_Match with Regular Expression:单词之间只有单个连字符和空格)
                            本文介绍了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:单词之间只有单个连字符和空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
				 沃梦达教程
				
			本文标题为:PHP preg_Match with Regular Expression:单词之间只有单个连字符和空格
				
        
 
            
        基础教程推荐
             猜你喜欢
        
	     - 使用 scandir() 在目录中查找文件夹 (PHP) 2022-01-01
 - 如何在数学上评估像“2-1"这样的字符串?产生“1"? 2022-01-01
 - 将变量从树枝传递给 js 2022-01-01
 - php中的foreach复选框POST 2021-01-01
 - Yii2 - 在运行时设置邮件传输参数 2022-01-01
 - Web 服务器如何处理请求? 2021-01-01
 - 主题化 Drupal 7 的 Ubercart “/cart"页 2021-01-01
 - php 7.4 在写入变量中的 Twig 问题 2022-01-01
 - PHPUnit 的 Selenium 2 文档到底在哪里? 2022-01-01
 - php中的PDF导出 2022-01-01
 
    	
    	
    	
    	
    	
    	
    	
    	
				
				
				
				