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
- They can contain upper and lower case letters, numbers, underscores, and hyphens.
- They can contain
=>as an exact string, not separate characters. - They cannot start with
=>. - They cannot finish with
=>.
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=>
Use negative lookarounds. Negative lookahead
(?!=>)at the beginning to prohibit beginning with=>, and negative lookbehind(?<!=>)at the end to prohibit ending with=>.DEMO