PHP regular expression prevents repeated string

Im trying to create a regular expression in PHP that checks if a string matches the following rules:

  • It has 1 - 7 occurrences of one of the following lines (Mon, Tue, Wed, Thu, Fri, Sat, Sun)
  • Lines separated by a,
  • case insensitive
  • Lines are not repeated.

I believe that I have completed the first three aspects of this:

/^(Mon|Tues|Wed|Thurs|Fri|Sat|Sun)(,(Mon|Tues|Wed|Thurs|Fri|Sat|Sun)){0,6}$/i 

I'm trying my best to prevent repetition. Can anyone advise?

+7
php regex
source share
2 answers
 ^(Mon|Tues|Wed|Thurs|Fri|Sat|Sun)(?:,(?!\1|\2)(Mon|Tues|Wed|Thurs|Fri|Sat|Sun)){0,6}$ 

You can use this if regex is an absolute requirement, but I would rather recommend Martijn. It is much more flexible and easier to read.

Here is how I tested this in PHP:

 <?php $subject1 = "Mon,Mon"; $subject2 = "Sun,Mon,Fri,Sun"; $subject3 = "Sat"; $subject4 = "Mon,Wed,Tues,Fri,Wed"; $subject5 = "Mon,Tues"; $pattern = '/^(Mon|Tues|Wed|Thurs|Fri|Sat|Sun)(?:,(?!\1|\2)(Mon|Tues|Wed|Thurs|Fri|Sat|Sun)){0,6}$/i'; print_r(preg_match($pattern, $subject1, $matches) . " " . $subject1 . "\n"); print_r(preg_match($pattern, $subject2, $matches) . " " . $subject2 . "\n"); print_r(preg_match($pattern, $subject3, $matches) . " " . $subject3 . "\n"); print_r(preg_match($pattern, $subject4, $matches) . " " . $subject4 . "\n"); print_r(preg_match($pattern, $subject5, $matches) . " " . $subject5 . "\n"); ?> 

It is output:

 0 Mon,Mon 0 Sun,Mon,Fri,Sun 1 Sat 1 Mon,Wed,Tues,Fri,Wed 1 Mon,Tues 
+5
source share

Do I need to be a regular expression? If not:

 $daysStart = 'Mon,Tues,Wed,mon'; $days = strtolower($daysStart); $days = explode(",", $days); // split on comma $days = array_unique($days); // remove uniques $days = implode(",", $days); // join on comma // Compare new string to original: if(strtolower($days)===strtolower($daysStart )){ /*match*/ } 

The result is a string of days, separated by commas. Not sure what you want as output, you might want to save the original input in other distant or ucfirst() values ​​with array_map() or something else, this will just show you a different method


Or my code is shorter:

 $daysStart = 'Mon,Tues,Wed,mon'; $days = explode(",", strtolower($daysStart ) ); $days = implode(",", array_unique($days) ); if(strtolower($days)===strtolower($daysStart )){ /*match*/ } 

or function (like a short code, maybe a longer version):

 function checkDays($string){ $days = explode(",", strtolower($string) ); $days = implode(",", array_unique($days) ); return (strtolower($days)===strtolower($daysStart)) ? true : false;// * } 

* I could only do the return and str checks, but I prefer to add true / false so that I am sure that the return value is always true for false as logical, and not true or false.

+5
source share

All Articles