phpregexvalidationpreg-matchcharacter-class

Validate string to contain only qualifying characters and a specific optional substring in the middle


I'm trying to make a regular expression in PHP. I can get it working in other languages but not working with PHP.

I want to validate item names in an array

My current code:

$regex = '/^[a-zA-Z0-9-_]+$/';    // contains A-Z a-z 0-9 - _
//$regex = '([^=>]$)';  // doesn't end with =>
//$regex = '~.=>~';  // doesn't start  with =>

if (preg_match($regex, 'Field_name_true2')) {
    echo 'true';
} else {
    echo 'false';
};
// Field=>Value-True
// =>False_name
//Bad_name_2=>

Solution

  • Use negative lookarounds. Negative lookahead (?!=>) at the beginning to prohibit beginning with =>, and negative lookbehind (?<!=>) at the end to prohibit ending with =>.

    ^(?!=>)(?:[a-zA-Z0-9-_]+(=>)?)+(?<!=>)$
    

    DEMO