检查字符串是否与模式匹配 [英] Check to see if a string matches a pattern

查看:44
本文介绍了检查字符串是否与模式匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

If I need a string to match this pattern: "word1,word2,word3", how would I check the string to make sure it fits that, in PHP?

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

I want to make sure the string fits any of these patterns:

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

推荐答案

使用 regular表达式:

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

这匹配:

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

但不是:

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

这篇关于检查字符串是否与模式匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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