Search code examples
phpregexvalidation

Validate that a string contains a month name, then anything, then a colon


I want to know the preg_match condition in PHP to check if a string starts with a month (January to December) and ends with a colon (:). In between, it can have any alphabet, character or number. Can someone please help? Stuck for an hour, not getting the right results.

For example, the string "December 2,&*&98hkjk:" should return true.

I got the pattern for Month and Colon using txt2re.com but I am having no clue how to form it and test the result.

$txt = 'May k!ur2!3:';

$re1 = '((?:Jan(?:uary)?|Feb(?:ruary)?|Mar(?:ch)?|Apr(?:il)?|May|Jun(?:e)?|Jul(?:y)?|Aug(?:ust)?|Sep(?:tember)?|Sept|Oct(?:ober)?|Nov(?:ember)?|Dec(?:ember)?))';   # Month 1
$re2 = '.*?';   # Non-greedy match on filler
$re3 = ':'; # Uninteresting: c
$re4 = '.*?';   # Non-greedy match on filler
$re5 = '(:)';   # Any Single Character 1

if ($c = preg_match_all ("/" . $re1 . $re2 . $re3 . $re4 . $re5 . "/is", $txt, $matches))
{
    $month1 = $matches[1][0];
    $c1 = $matches[2][0];
    echo "Matched \n";
}
else
{
    echo "No match";
}

GOT THE SOLUTION:

$txt = $_POST['wtfb'];
         
$re1 = '((?:Jan(?:uary)?|Feb(?:ruary)?|Mar(?:ch)?|Apr(?:il)?|May|Jun(?:e)?|Jul(?:y)?|Aug(?:ust)?|Sep(?:tember)?|Sept|Oct(?:ober)?|Nov(?:ember)?|Dec(?:ember)?))'; # Month 1

$re4 = '.*?';   # Non-greedy match on filler
$re5='(:)'; # Any Single Character 1

if ($c = preg_match_all ("/" . $re1 . $re4 . $re5 . "/is", $txt, $matches))
{
    $month1 = $matches[1][0];
    $c1 = $matches[2][0];
    echo 'Match';
}
else 
{ 
    echo 'No match'; 
}

Solution

  • You can use strpos to check a word in string.

    $str = "December 2,&*&98hkjk:";
    
    //Check for `December`
    if(strpos($str, 'December') !== false) { // use === for type comparison 
       //do your stuff
        echo 'Match';
    }else{
        echo 'No Match';
    }
    

    strpos() in much simpler solution for this.

    This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE. Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.