これは、ファイル名を取得し、そのコンテンツをロードして文字列を生成する方法です。
$pattern = '/(.*<!--#include\s*file\s*=\s*")(.*?)("\s*-->.*)/s';
$subject = '<!--#include file="footer.html" -->';
if (preg_match($pattern, $subject, $regs)) {
$prefix = $regs[1];
$fileName = $regs[2];
$suffix = $regs[3];
// Load data from file (implement this by yourself).
$fileData = loadDataFromFile($fileName)
$myFinalCompleteString = $prefix . $fileData . $suffix;
}
パターンの説明は次のとおりです。
# (.*<!--#include\s*file\s*=\s*")(.*?)("\s*-->.*)
#
# Options: dot matches newline
#
# Match the regular expression below and capture its match into backreference number 1 «(.*<!--#include\s*file\s*=\s*")»
# Match any single character «.*»
# Between zero and unlimited times, as many times as possible, giving back as needed (greedy) «*»
# Match the characters “<!--#include” literally «<!--#include»
# Match a single character that is a “whitespace character” (spaces, tabs, and line breaks) «\s*»
# Between zero and unlimited times, as many times as possible, giving back as needed (greedy) «*»
# Match the characters “file” literally «file»
# Match a single character that is a “whitespace character” (spaces, tabs, and line breaks) «\s*»
# Between zero and unlimited times, as many times as possible, giving back as needed (greedy) «*»
# Match the character “=” literally «=»
# Match a single character that is a “whitespace character” (spaces, tabs, and line breaks) «\s*»
# Between zero and unlimited times, as many times as possible, giving back as needed (greedy) «*»
# Match the character “"” literally «"»
# Match the regular expression below and capture its match into backreference number 2 «(.*?)»
# Match any single character «.*?»
# Between zero and unlimited times, as few times as possible, expanding as needed (lazy) «*?»
# Match the regular expression below and capture its match into backreference number 3 «("\s*-->.*)»
# Match the character “"” literally «"»
# Match a single character that is a “whitespace character” (spaces, tabs, and line breaks) «\s*»
# Between zero and unlimited times, as many times as possible, giving back as needed (greedy) «*»
# Match the characters “-->” literally «-->»
# Match any single character «.*»
# Between zero and unlimited times, as many times as possible, giving back as needed (greedy) «*»