试试这个:
$string = 'Writing to tell you that var MyCode = "dentline"; Learn it.';
$matches = array();
preg_match('/var MyCode = "(.*?)";/', $string, $matches);
echo $matches[1];
结果:
dentline
ideone
说明
var MyCode = " Match this string literally and exactly
( Start a capturing group.
.*? Match any characters, as few as possible (not greedy)
) End the capturing group.
"; Match the closing double quote followed by a semi-colon
的捕获组“捕获”匹配的内容并将其存储在数组$matches
中,以便之后可以访问它。
关于这些构造的更多信息可以在这里找到:
变化
如果 “mycode的” 可以改变,然后用这个来代替:
preg_match('/var \w+ = "(.*?)";/', $string, $matches);
在这个表达式中\w
表示“匹配任何字符”。您可能还想使用\s+
而不是空格,以便您可以匹配一个或多个任何空格字符(也是制表符和换行符)。同样,\s*
匹配零个或多个空格。所以你尝试的另一种可能性是:
preg_match('/var\s+\w+\s*=\s*"(.*?)"\s*;/', $string, $matches);
请问你的字符串总是被双引号,而不是单引号?你的字符串是否包含转义引号?代码中的空格是否有意义?变量名称始终是“MyCode”还是可以是其他名称? – 2010-10-04 22:47:16
字符串总是用双引号。没有转义字符,没有空格,没有变量名称。就像一样。 – 2010-10-04 23:48:08