您要做的是将整个文件内容作为单个字符串读取,然后根据您在其中找到的内容将其拆分。如下:
// Read the contents of the file into $file as a string
$mainfilename = "/path/to/file.txt";
$handle = fopen($mainfilename, "r");
$file = fread($handle, filesize($mainfilename));
fclose($handle);
/* $file contains your file contents
* $findme contains "Found an XML file"
* $splitter contains "Closing XML file"
*/
// We only do anything if the string "Closing XML file" is inside the file
// in a place other than at the beginning of the file
if (strpos($file, $splitter) > 0) {
// Break up $file into pieces by splitting it along "Closing XML file"
$parts = explode($splitter, $file);
// Traverse the newly-formed pieces
foreach ($parts as $part) {
// If we have "Found an XML file" contained in this piece of the file
if (strpos($part, $findme) !== false) {
// Split up our smaller string around "Found an XML file"
$foundparts = explode($findme, $part);
// The last piece will always contain the filename,
// but only if there are two or more pieces
// i.e. something between the strings
if (count($foundparts) > 1) $filename = array_pop($foundparts);
/* Do whatever you want with $filename */
}
}
}
这将做的是,假设$file == "Closing XML file gibberish goes here Found an XML file garbage Found an XML file filename.xls Closing XML file more gibberish"
:
- 检查以确保关闭 XML 文件存在于
$file
开头以外的位置 - 它位于结尾附近。
- 分成
$file
几块:$parts = ['', ' gibberish goes here Found an XML file garbage Found an XML file filename.xls ', ' more gibberish']
- 遍历
$parts
寻找“找到一个 XML 文件”的实例 -$parts[1]
有它
- 分成
$parts[1]
几块:$foundparts = [' gibberish goes here',' garbage ', ' filename.xls ']
- 如果 中至少有 2 个部分
$foundparts
,则“弹出”最后一个元素$foundparts
,因为它始终是包含文件名的元素
- 你现在有了文件名
$filename
,你可以随意使用
注意:这些函数是区分大小写的,所以如果您还想查找“找到一个 xml 文件”的实例(xml 为小写),您需要对所有 , , 进行一些字符串转换为$file
全部$splitter
小写和$findme