1

我正在使用一些正则表达式(有效),但实际上并不了解它在做什么。作为一名科学家,我喜欢跟随我所做的一切!

代码来自这个 SO 答案:https ://stackoverflow.com/a/118886/889604

$mtime = filemtime($_SERVER['DOCUMENT_ROOT'] . $file);
return preg_replace('{\\.([^./]+)$}', ".$mtime.\$1", $file);

此代码采用文件名(例如/files/style.css),并添加文件的mtime(例如/files/styles.1256788634.css)。

所以,我明白了^$符号是要匹配的字符串的开头和结尾,并且可以./多次匹配任何字符(因为+),但是mtime文件名和扩展名之间的结果如何呢?

4

3 回答 3

1

The { and } are used as delimiters and do not take part of the search pattern. \\.is describing a dot. The dot has to be escaped (thus the backslashes) because a un-escaped dot would describe the presence of any single character. The round brackets ( ... ) define a group that can be accessed via $1 in the second preg_replace parameter. The content of this group consists of [^./]+, which means

a positive quantity of (defined via the + after the set) any single character that is not (^ in the beginning of a set means not) a dot . or a slash /.

The round brackets are followed by a $ which describes the end of the line.

The expression will match the file extension of the path, like .css, while css will be the value of the group $1. Therefore, .css will be replaced with .$mtime.css where $mtime will be the value of the php variable.

于 2013-03-23T15:43:26.100 回答
0

由于mtimePHP 的字符串插值规则,最终出现在输出中,这导致在双引号字符串中引用的变量输出变量的值而不是变量名称的文字文本。有关更多信息,请参见http://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.double(本节最后一句)。

于 2013-03-23T15:39:57.813 回答
0

正则表达式模式所做的只是替换整个文件扩展名并使用括号将.css不带句点的扩展名存储到捕获中。然后它用一个句点、 的值、另一个句点以及从 regex 中捕获的扩展替换来自 的扩展。css([^./]+).css$file$mtime$1

并注意:^并不意味着字符串的开头。当它在一个组中时,就像[^./]它说“匹配除了这些字符之外的任何字符”

我希望这一切都是有道理的。

编辑:它只匹配 $file 的 .css 部分,因为\\.它告诉正则表达式从 $file 中找到的第一个句点开始,然后继续进行捕获。它必须用 the 转义,\\.否则它会像匹配任何字符的正则表达式句点一样。

于 2013-03-23T15:40:17.020 回答