phpregexpreg-matchdelimiter

Regex without pattern delimiters doesn't emit Warning with preg_match()


$first = ".";
$last = "a";
$middle= "testing-123.test";

if (preg_match("[a-zA-Z0-9]", $first)){
 echo 'Frist Returned valid.';
}
if (preg_match("[a-zA-Z0-9.-]", $middle)){
 echo 'Middle Returned valid.';
}
if (preg_match("[a-zA-Z0-9]", $last)){
 echo 'Last Returned valid.';
}

I am breaking down a string into 3 parts using substr so in this example the original text was ".testing-123.testa". I didnt include the substr here but just predefined the variables in this case. I want to check so it means the following requirements:

First character: a-z, A-Z, 0-9 NO SYMBOLS

middle character: a-z, A-Z, 0-9, only . and - symbols

Last character: same as first character.

When I ran above code it echo'd nothing. Any ideas?


Solution

  • You are missing delimitters, try adding / around your regex:

    if (preg_match("/[a-zA-Z0-9]/", $first)){
     echo 'Frist Returned valid.';
    }
    if (preg_match("/[a-zA-Z0-9.-]/", $middle)){
     echo 'Middle Returned valid.';
    }
    if (preg_match("/[a-zA-Z0-9]/", $last)){
     echo 'Last Returned valid.';
    }
    

    You might also want to use preg_match_all to find more/all instances.