Reputation: 4185
I have this function to determine if a word is between single/double quotes but it gives a false positive if the word is between two closed quotes.
function keyword_in_quotes( $str, $word ) {
echo $str . "\n";
if (preg_match('/["\'].*\b' . $word . '\b.*["\']/m', $str))
echo $word . " found in quotes.\n";
else
echo $word . " NOT found in quotes.\n";
}
// this call correctly reports KEYWORD is between quotes
keyword_in_quotes( "Sentence with a 'Specific KEYWORD and other words' in quotes", "KEYWORD" );
// this call incorrectly reports KEYWORD is between quotes
keyword_in_quotes( "Sentence with a 'lead quote' and KEYWORD not in 'quotes' or 'even this'", "KEYWORD" );
Which gives the results:
Sentence with a 'Specific KEYWORD and other words' in quotes
KEYWORD found in quotes.
Sentence with a 'lead quote' and KEYWORD not in 'quotes' or 'even this'
KEYWORD found in quotes.
I'm a bit out of my depth. How can I determine if the given word is only between OPEN quotes? (No limit on number of quotes in the string).
Upvotes: 1
Views: 747
Reputation: 785196
You can use this regex instead to determine if KEYWORD
is not in quotes:
'[^']*'(*SKIP)(*F)|KEYWORD
Upvotes: 3