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_file
或parse_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.
编辑,您可能还想考虑转义引号,请改用以下正则表达式:
'~"((?:[^\\\\"]+|\\\\.)*)"~'
这种模式更难缠住你的头。本质上,这分为两个可能的匹配项(由 Regex OR 字符分隔|
)
[^\\\\"]+ //match any character that is NOT a backslash and is NOT a double quote
| //or
\\\\. //match a backslash followed by any character.
逻辑非常简单,第一个字符类将匹配除双引号或反斜杠之外的所有字符。如果找到引号或反斜杠,正则表达式会尝试匹配组的第二部分。如果它是反斜杠,它当然会匹配 pattern \\\\.
,但它也会将匹配提前 1 个字符,有效地跳过反斜杠后面的任何转义字符。该模式唯一会停止匹配的情况是遇到单独的未转义双引号时,