2

I have a path that looks like:

/home/duke/aa/servers/**servername**/var/...morefiles...

With php, I want to extract the "servername" from the path

Unfortunately I'm not that well versed with php but I came up with something that used strstr() but I am only using PHP version 5.2 where as one of the parameter functions require 5.3

What could be some code that would return "servername"?

dukevin
  • 22,384
  • 36
  • 82
  • 111
  • What do you mean by "extract" exactly? Do you know the server name? If not, what tells the server name apart from everything else? – Pekka Jul 12 '11 at 20:09
  • there are a bunch of folders in /servers/ that represent servername. But my question is I want some function to return **servername** – dukevin Jul 12 '11 at 20:11
  • Please show more examples of `...morefiles...` – powtac Jul 12 '11 at 20:11
  • 1
    Is the portion of the string before '\*\*servername\*\*' always the same ('/home/duke/aa/servers/'). If not, what variations are possible? – George Cummins Jul 12 '11 at 20:11
  • @George the portion of the string before servername is always the same – dukevin Jul 12 '11 at 21:00

3 Answers3

8

you can use explode('/', $path) to break it down into the individual directories. After that, it's up to you to figure out which array element is the server name (with your sample path, it'd be #4):

$parts = explode('/', $path);
echo $parts[4]; // **servername**
Marc B
  • 356,200
  • 43
  • 426
  • 500
6
function getServerName($data) {
    preg_match('#/servers/(.+)/var/#', $data, $result);
    if (isset($result[1]) {
        return $result[1];
    }
}

$data = '/home/duke/aa/servers/**servername**/var/...morefiles...';
echo getServerName($data);
powtac
  • 40,542
  • 28
  • 115
  • 170
  • will this working using `+` as the delimiter and having an unescaped `+` in the middle? I would guess you get an unknown modifier ')' error or something about not closing the group. – Jonathan Kuhn Jul 12 '11 at 20:12
  • thanks this looks promising, I will try this out when I get home! – dukevin Jul 12 '11 at 20:14
0

$str = '/home/duke/aa/servers/**servername**/var/...morefiles...';

echo preg_replace('$(.+)/servers/(.+)/var/(.+)$', '\2', $str);
Buddy
  • 1,808
  • 3
  • 19
  • 28