$re = '/^(([^"\']*?)foo(.*)|(.*?)foo([^"\']*))$/m';
$str = 'hello foo
hello "foo" and foo not \'foo\'
Hello "foo" foo, how are "you" doing?
they "are foo and bar" and foo
This foo " is too a match
"foo" not bar but foo
This foo \' should be matched
Then foo said "foo bar", which didn\'t work
"This is the foo bar"
hello "foo"
hello "foo"
hello \'foo\'
you said "my name is foo"
';
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