需要一个匹配“word1,word2,word3”的正则表达式

时间:2010-09-23 09:18:21

标签: php regex

我正在尝试构建一个与模式匹配的正则表达式:

word1, word2, word3

所以基本上我希望“”出现两次并在它们之间有单词。到目前为止,我提出了:

$general_content_check = preg_match("/^.*, .*$/", $general_content);

但这只是在字符串中多次匹配“”。

有人可以帮我这个吗?

2 个答案:

答案 0 :(得分:7)

这取决于你对“单词”的意思,但你可以从尝试这个开始:

^[^,]+(?:, +[^,]+){2}$

说明:

^          Start of line/string.
[^,]+      A "word" (anything that isn't a comma - including whitespace, etc.)
(?:        Start non-capturing group
    , +    A comma then any number of spaces
    [^,]+  A word
)          Close group
{2}        Repeat group exactly two times
$          End of line/string.

“word”的其他可能定义:

  • 除空白或逗号外的任何内容:[^\s,]+
  • 只有A-Z中的字母:[A-Z]+(可选择添加不区分大小写的标记)
  • 任何语言的Unicode字母:\p{L}+(不广泛支持)
  • 等等...

答案 1 :(得分:4)

尝试

"/^\w+, \w+, \w+$/"
相关问题