Jump to content

REGEX Help (I hate this stuff)


coreysnyder04

Recommended Posts

Below I have this code to break apart a string that contains scores and will follow this format:

  Worthington 3 Byrne's Pub 2

  Net Jets 3 Roosters 2

  VFW Patriots 5 Garage Bar 1

  Fireballs 4 Rhinos 1

 

The code does a good job of this, but I'm running into problems where teams have names with numbers in them such as:

    BT3 3 Ohio Mayhem 0

    Hockey 101 2 Same Day Sports 1

 

Any ideas on how to modify my regex to catch this issue??

 

if (preg_match_all("/([a-zA-Z\s\.\'\/]*)([0-9])([a-zA-Z\s\.\'\/]*)([0-9])+/", $scoresArray[$i], $matches)) {	
		//echo "Scores Match Found <br />";
		$team1 = ($matches[1][0]);
		$score1 = ($matches[2][0]);
		$team2 = ($matches[3][0]);
		$score2 = ($matches[4][0]);
		echo "<br />".$team1.": ".$score1."   ||    ".$team2.": ".$score2."<br />";
	}

Link to comment
https://forums.phpfreaks.com/topic/184587-regex-help-i-hate-this-stuff/
Share on other sites

Based on what I've seen thus far, one possible solution could be:

 

Example

$str = "
Worthington 3 Byrne's Pub 2
Net Jets 3 Roosters 2
VFW Patriots 5 Garage Bar 1
Fireballs 4 Rhinos 1
BT3 3 Ohio Mayhem 0
Hockey 101 2 Same Day Sports 7";

preg_match_all('#([a-z0-9.\'\s/]+?)\s(\d+)\s(?=\D)([a-z0-9.\'\s/]+?)\s(\d+)#i', $str, $matches, PREG_SET_ORDER);
foreach ($matches as $val) {
    echo "$val[1]: $val[2]  ||	$val[3]: $val[4]<br />";
}

 

Output:

Worthington: 3 || Byrne's Pub: 2
Net Jets: 3 || Roosters: 2
VFW Patriots: 5 || Garage Bar: 1
Fireballs: 4 || Rhinos: 1
BT3: 3 || Ohio Mayhem: 0
Hockey 101: 2 || Same Day Sports: 7

 

There is one crux in all this though.. and that is this part of the pattern; \s(\d+)\s(?=\D). The (second) team name cannot start with a digit.. this part of the pattern looks for the sequence of space, one or more digits, then space again (providing the next character afterwards is NOT a digit - represented by \D, it's late for me, and that is how I managed to have regex differentiate between that and a regular space, \d+, space, which alone wouldn't work). I noticed you have dots and slashes in your pattern (so I can only assume that those characters might show up in a team's name - so I left those in there as well).

 

My apologies.. I'm tired and must now catch some serious z's.  :sleeping:

Hopefully, this solution provides a kickstart that you can use moving forward from here.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.