获取初始化的字符串正则表达式


get initialized string regex

kNO = "Get this value now if you can";

如何从该字符串中获取Get this value now if you can?这看起来很容易,但我不知道从哪里开始。

首先阅读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

根据您获取输入的方式,您可以使用 parse_ini_fileparse_ini_string 。死简单。

使用字符类开始从一个左引号提取到下一个引号:

$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 个字符,有效地跳过反斜杠后面的任何转义字符。此模式停止匹配的唯一时间是遇到单独的、未转义的双引号时,