【问题标题】:Check to see if a string matches a pattern检查字符串是否与模式匹配
【发布时间】:2010-12-19 03:00:23
【问题描述】:

如果我需要一个字符串来匹配这个模式:“word1,word2,word3”,我将如何检查字符串以确保它适合 PHP?

我想确保字符串符合以下任何模式:

word
word1,word2
word1,word2,word3,
word1,word2,word3,word4,etc.

【问题讨论】:

    标签: php regex string


    【解决方案1】:

    使用regular expressions:

    preg_match("[^,]+(,[^,]+){2}", $input)
    

    这匹配:

    stack,over,flow
    I'm,not,sure
    

    但不是:

    ,
    asdf
    two,words
    four,or,more,words
    empty,word,
    

    【讨论】:

      【解决方案2】:
      preg_match('/word[0-9]/', $string);
      

      http://php.net/manual/en/function.preg-match.php

      【讨论】:

      • 我觉得他不是这个意思。
      • 很抱歉。使用多种语言的副作用。 Ruby 将采用文字。 (或将 '' 解释为分隔符。)
      【解决方案3】:

      如果您只想匹配一个或多个完整的单词而不是逗号分隔的短语,请尝试:

        preg_match("^(?:\w+,)*\w+$", $input)
      

      【讨论】:

        猜你喜欢
        • 2012-09-17
        • 2018-04-03
        • 1970-01-01
        • 1970-01-01
        • 2016-10-03
        • 1970-01-01
        • 2011-03-28
        • 1970-01-01
        相关资源
        最近更新 更多