joshkrz
joshkrz

Reputation: 519

Problems matching a string to a regular expression

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:

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:

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.

Upvotes: 1

Views: 76

Answers (2)

James Coyle
James Coyle

Reputation: 10418

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.

Upvotes: 1

Cjueden
Cjueden

Reputation: 1200

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/

Upvotes: 1

Related Questions