我有一个.txt文件,如下所示:
Title: Test
Author: zad0xsis
Date: July 13th, 2011
Body: This is a test post and this can continue until the file end
如何让PHP识别“标签”并将内容转换为新字符串?提前致谢! :d
答案 0 :(得分:5)
$fc = file('some_file.txt'); // read file into array
foreach ($fc as $line) {
list($tag, $content) = explode(':', $line, 2);
// do something here
}
现在,每个文件中有多个不相关的集合吗?如果是这样,你将不得不寻找一些标记,也许是一个新行,并进行重置。希望你能自己解决这个问题。
您可以查看一些功能:
file
file_get_contents
explode
list
(不是真正的功能)$fc = file('some_file.txt'); // read file into array
foreach ($fc as $index => $line) {
list($tag, $content) = explode(':', $line, 2);
// do something here
if ('body' == strtolower($tag)) {
$content = join(array_slice($fc, $index + 1, count($fc)));
break;
}
}
为您提供更多功能!
strtolower
join
(aka implode
) array_slice
trim
- 我的解决方案中没有使用它,但您可能希望使用它来修剪file()
返回的行末尾的换行符。或者,您可以在致电FILE_IGNORE_NEW_LINES
时使用file()
标记,有关详细信息,请参阅PHP Manual entry for file()
(也在上面链接)。答案 1 :(得分:3)
另一种解决方案:demo here
<?php
//$sample = file_get_contents('myfile.txt'); // read from file
$sample = "Title: Test
Author: zad0xsis
Date: July 13th, 2011
Body: This is a test post and this can continue until the file end";
$re = '/^(?<tag>\w+):\s?(?<content>.*)$/m';
$matches = null;
if (preg_match_all($re, $sample, $matches))
{
for ($_ = 0; $_ < count($matches['tag']); $_++)
printf("TAG: %s\r\nCONTENT: %s\r\n\r\n", $matches['tag'][$_], $matches['content'][$_]);
}
产生
TAG: Title
CONTENT: Test
TAG: Author
CONTENT: zad0xsis
TAG: Date
CONTENT: July 13th, 2011
TAG: Body
CONTENT: This is a test post and this can continue until the file end
以为我只为GP使用命名标签。 此外,如果需要,您可以将(?<tag>\w+)
替换为更加模糊的内容,例如(?<tag>.*?)
,如果可能有空格,数字等
答案 2 :(得分:2)
<?php
$tagValue = array();
$file = fopen("welcome.txt", "r") or exit("Unable to open file!");
while(!feof($file))
{
$line = fgets($file);
$tagDelimiter = strpos ($line ,":");
$tag = substr($line,0,$tagDelimiter);
$value = substr($line,$tagDelimiter+1,strlen($line)-$tagDelimiter);
$tagValue[$tag] = $value;
}
fclose($file);
?>
您可以访问您的数据:$tagValue["Title"]
答案 3 :(得分:2)
$file = file("file.txt");
foreach($file as $line)
{
preg_match("|(.*?): (.*?)|", $line, $match);
$tag = $match[1];
$content = $match[2];
}
答案 4 :(得分:1)
你可以这样做:
$file = file('file.txt');
foreach($file as $line)
{
if(preg_match('/(.*) : (.*)/iUs', $line, $match)
{
$tag = $match[1];
$value = $match[2]
}
}
答案 5 :(得分:0)