1

I am creating some intranet software and to determine which room number and PC number the computer is in I am using the REMOTE_HOST server array.

Here is my code:

$hostname = $_SERVER['REMOTE_HOST'];
//Check to see if the computer name is compatible with room auto-detect
if (preg_match("/G|F\d{1,2}-.*?-PC\d{1,2}.*?/i", $hostname)) {
    $room = explode("-", $hostname);
    $pc = explode(".", $room[2]);
} else {
    $pc[0] = "NA";
    $room[0] = "other";
}

This statment needs to be true if the computer names are something like these:

  • g22-dell-pc23.roundhay.local
  • f48-lenovo-pc02.roundhay.local
  • g6-asus-pc18.roundhay.local

If the statement is not as above then it needs to revert the room and pc array to NA and Other.

I can extract the room number and PC successfully but when a PC with a non standard name uses the software it still tries to extract the information and the software fails because it has no information to go on.

For example:

g22-smartboard.roundhay.local

The software still tries to get the PC number, even though it dosent match my regular expression. However on my testing PC with the computer name JOSH-PC it does fall back onto the default information.

I have tested my regular expression and it seems to be true whenever the name starts with either a G or an F.

I need it to match specifically to these requirements:

  • First letter is G or F
  • Then either one or two digits from 0 - 9
  • Then a -
  • Then any amount of letters a-z
  • Then a -
  • Then the letters PC
  • Then either one or two digits from 0 - 9
  • Then anything

I have tried all sorts to get this to work but I just don't understand regex properly. I have looked it up but its just all too confusing.

Hugo Dozois
  • 8,147
  • 12
  • 54
  • 58
joshkrz
  • 499
  • 3
  • 7
  • 25

2 Answers2

1

The regular expression:

/[g|f]\d{1,2}-[a-z]+-pc\d{1,2}.+/i

Should work. I use http://gskinner.com/RegExr/ to build expressions.

James Coyle
  • 9,922
  • 1
  • 40
  • 48
1

Try this RegEx [G|F]\d{1,2}-[a-z]+-pc\d{1,2}.+

Also a great resource for regex is http://gskinner.com/RegExr/

Cjueden
  • 1,200
  • 2
  • 13
  • 25