$re = '/^(?!(?:(?!g1|g2).)*(?:g21|g22)(?:(?!g31|g32|g41|g42).)*(?:g11|g12)).*?(?:g11|g12).*$/m';
$str = '\'g11\'
\'g31 g11\'
\'g41g11\'
\'g11 g21 g11\'
\'anything or nothing g11 anything or nothing\'
\'anything or nothing g31 anything or nothing g11\'
\'anything\'
\'\'
\'g31 g21 g11\'
\'g21 g11 g31\'
';
preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);
// Print the entire match result
var_dump($matches);
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for PHP, please visit: http://php.net/manual/en/ref.pcre.php