Skip to content

Commit 801e336

Browse files
authored
Merge pull request #77 from clue-labs/hosts-whitespace
Ignore whitespace from hosts file
2 parents f6b38d7 + bbaa260 commit 801e336

File tree

2 files changed

+11
-2
lines changed

2 files changed

+11
-2
lines changed

src/Config/HostsFile.php

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -81,7 +81,7 @@ public static function loadFromPathBlocking($path = null)
8181
public function __construct($contents)
8282
{
8383
// remove all comments from the contents
84-
$contents = preg_replace('/ *#.*/', '', strtolower($contents));
84+
$contents = preg_replace('/[ \t]*#.*/', '', strtolower($contents));
8585

8686
$this->contents = $contents;
8787
}
@@ -131,7 +131,7 @@ public function getHostsForIp($ip)
131131

132132
$names = array();
133133
foreach (preg_split('/\r?\n/', $this->contents) as $line) {
134-
$parts = preg_split('/\s+/', $line);
134+
$parts = preg_split('/\s+/', $line, null, PREG_SPLIT_NO_EMPTY);
135135
$addr = array_shift($parts);
136136

137137
// remove IPv6 zone ID (`fe80::1%lo0` => `fe80:1`)

tests/Config/HostsFileTest.php

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -108,6 +108,15 @@ public function testReverseLookup()
108108
$this->assertEquals(array(), $hosts->getHostsForIp('192.168.1.1'));
109109
}
110110

111+
public function testReverseSkipsComments()
112+
{
113+
$hosts = new HostsFile("# start\n#127.0.0.1 localhosted\n127.0.0.2\tlocalhost\t# example.com\n\t127.0.0.3\t\texample.org\t\t");
114+
115+
$this->assertEquals(array(), $hosts->getHostsForIp('127.0.0.1'));
116+
$this->assertEquals(array('localhost'), $hosts->getHostsForIp('127.0.0.2'));
117+
$this->assertEquals(array('example.org'), $hosts->getHostsForIp('127.0.0.3'));
118+
}
119+
111120
public function testReverseNonIpReturnsNothing()
112121
{
113122
$hosts = new HostsFile('127.0.0.1 localhost');

0 commit comments

Comments
 (0)