2012-06-04 19 views

回答

2

首先阅读PHP PCRE并查看示例。对于你的问题:

$str = 'kNO = "Get this value now if you can";'; 
preg_match('/kNO\s+=\s+"([^"]+)"/', $str, $m); 
echo $m[1]; // Get this value now if you can 

说明:

kNO  Match with "kNO" in the input string 
\s+  Follow by one or more whitespace 
"([^"]+)" Get any characters within double-quotes 
+0

感谢您的解释 – Michelle

+0

虽然不需要'?'。 –

+0

@JasonLarke你是对的。我编辑了我的答案,谢谢。 – flowfree

1

使用字符类开始从一个开放的报价提取到下一个:

$str = 'kNO = "Get this value now if you can";' 
preg_match('~"([^"]*)"~', $str, $matches); 
print_r($matches[1]); 

说明:

~ //php requires explicit regex bounds 
" //match the first literal double quotation 
( //begin the capturing group, we want to omit the actual quotes from the result so group the relevant results 
[^"] //charater class, matches any character that is NOT a double quote 
* //matches the aforementioned character class zero or more times (empty string case) 
) //end group 
" //closing quote for the string. 
~ //close the boundary. 

编辑,您可能还需要考虑到转义引号,使用下面的正则表达式来代替:

'~"((?:[^\\\\"]+|\\\\.)*)"~' 

这种模式稍微有点困难的绕到你的头。本质上,这被分成两个可能的匹配(由正则表达式或字符|分隔)

[^\\\\"]+ //match any character that is NOT a backslash and is NOT a double quote 
|   //or 
\\\\.  //match a backslash followed by any character. 

逻辑是非常简单的,第一个字符类将匹配除了双引号或反斜杠所有字符。如果找到引号或反斜线,则正则表达式会尝试匹配组的第二部分。如果它是一个反斜杠,它当然会匹配\\\\.的模式,但它也会将匹配提前1个字符,有效地跳过反斜杠后面的任何转义字符。唯一一次遇到一个孤独的,转义双引号时,这种模式将停止匹配,

+0

感谢您的深入解释。 – Michelle

相关问题