Reading text after a certain character in php

孤街醉人 提交于 2019-12-12 22:25:29

问题


Okay so I have a text file and inside of the text file I have these lines:

IP = 127.0.0.1
EXE = Client.exe
PORT = 8080
TITLE = Title
MAINT = False
MAINT-Message = This is the message.

what I am wanted to do is get the 'False' part on the fifth line.

I have the basic concept but I can't seem to make it work. This is what I have tried:

<?php
$file = file_get_contents('LauncherInfo.txt');
$info = explode(' = ', $file);

echo $info[5];
?>

And with this I get a result but when I echo $info[5] it gives me 'False Maint-Message' so it splits it but it only splits at the = sign. I want to be able to make it split at the where I have pressed enter to go onto the next line. Is this possible and how can I do it?

I was thinking it would work if I make it explode on line one and then do the same for the second line with a loop until it came to the end of the file? I don't know how to do this though.

Thanks.


回答1:


I think you're looking for the file(), which splits a file's contents into an array of the file's lines.

Try this:

$file = file('LauncherInfo.txt');
foreach ($file as $line) {
    if ($line) {
        $splitLine = explode(' = ',$line);
        $data[$splitLine[0]] = $splitLine[1];
    }
}
echo $data['MAINT'];



回答2:


Just in case you were curious, since I wasn't aware of the file() function. You could do it manually like this

<?php
$file = file_get_contents('LauncherInfo.txt');
$lines = explode("\n", $file);
$info=array();
foreach($lines as $line){
  $split=explode(' = ',$line);
  $info[]=$splitline[1];
}
echo $info[5];//prints False
?>


来源:https://stackoverflow.com/questions/17330591/reading-text-after-a-certain-character-in-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!