简体   繁体   中英

How to write regex pattern for checking comma separated values in php?

I have list of options which is coming from the request parameters from that i want to identify if it's comma separated values or not,please help me to achieve this thing..

List of items like this: subscriptions,discounts,users,values

my requirement is any number of values(only alphabets) which is separated by comma i want to identify that.

valid-scenarios :

users,Plans,discounts

users,plans,discounts,subscriptions,details

Invalid-scenarios :

,users,plans

users

users,plans,

switch($request->obj){
 case ' ':
   //do some code
 case 'preg_match()':{
 //do some code
}
}

So, you can use explode() to seperate the values from each other and then simply check if first or last value is empty or not. Note that you can use both an array or a string as values for $the_row_values.

$temp = explode(',',$the_row_values);

if ($temp[0] == ''){
  // Then Invalid
} elseif (array_pop($temp) == '') {
  // Then last value is empty ( something, and then nothing...)
} else {
  // Here you meet your valid requirments.
}

Results:

if (,user,hello,hi ) then: Invalid

if ( user,hello,hi,) then: Invalid

if ( user,hi,hello ) then: Valid

this regex should help

^[^,].*[^,]$

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM