Question

Looking for some help on how to validate a string in PHP.

The format to validate against is

X.XXam[d[i]-d[i] Only]

A sample entry could be:

8:55pm[Tues-Thurs Only]

d[i] represents an associative array value depending on the day of the week. For instance, the above contains Saturday and Sunday.

I need to make sure/validate this before inserting in the DB.

Can I get some help with this?

Was it helpful?

Solution 2

Check out regex 101. It is a wonderfull Tool to create regular expressions and understand them. From there i got this solution for you:

%^\d{1,2}:\d{1,2}([ap])m\[(Mon|Tue|Wed|Thu|Fri|-){1,} Only\]$%mg

The first bit (\d{1,2}) accepts a number between 0 and 99, then a : and another number between 0 and 99. Then it is either a or p followed by m. Then you have either Mon or Tue or .... or - for 1 to endles times.

At the end you have the modifiers g and m. The m is to make use of the ^ and $ modifiers that represent the beginning and the end of a line. The g is just to find ALL results rather than the first existing. You can leave that out.

To use Weekdays from an array called $array simply implode it to a string and fill it into your expression like this:

$weekdaysString = implode('|',$array);
$regex = '%^\d{1,2}:\d{1,2}([ap])m\[('.$weekdaysString.'|-){1,} Only\]$%mg';

Read up on implode.

OTHER TIPS

this should work for your case :

^\d{1,2}:\d{2}[ap]m\[\w+\-\w+ Only]$

demo here : http://regex101.com/r/mH9lX1

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top