PHP如何确定一个单词是否在字符串中的两个开放引号之间?

时间:2014-11-19 21:30:33

标签: php regex preg-match

我有这个函数来确定一个单词是否在单引号/双引号之间,但如果单词在两个封闭引号之间,它会给出误报。

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" );

结果如下:

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.

我有点超出我的深度。如何确定给定单词是否仅在OPEN引号之间? (字符串中的引号数量没有限制。)

1 个答案:

答案 0 :(得分:3)

您可以使用此正则表达式来确定KEYWORD是否不在引号中:

'[^']*'(*SKIP)(*F)|KEYWORD

RegEx Demo