Jump to content

Split this NBA result (one line) into four pieces?


tmallen

Recommended Posts

Here's the string I can parse in with an RSS feed:

// Returns true
"Hornets 118, Knicks 110 (F)" == $scores['channel']['item'][0]['title'];

So I'm working with scores in the format: "TeamA ScoreA, TeamB ScoreB (F)". I'd like to be able to break up the above string into these four parts, and have it work for various game results: "TeamA", "ScoreA", "TeamB", "ScoreB".

 

I understand that I can do this with Regex, and I even have a good idea of what my rules should be to grab these parts. I just can't translate them into Regex. "TeamA" begins with a Capital letter and ends with a lower-case letter preceding a space and a number. "ScoreA" is any number of digits, ending with a comma. I can strip the comma later, or exclude it with the search, whichever is easier. "TeamB" begins with the first capital letter after that comma and ends with a lower-case letter before a space, before a parentheses.

 

What regex patterns, using preg_match($pattern, $input, $output), I'm assuming, will do this?

Here's my working solution. It's far from perfect, but gets the job done well. Any advice about the regex, especially if I can somehow remove the need for my two substr() calls, will be much appreciated. Thanks!

 

for ($i=0; $i < 10; $i++) {
        echo "<a href=\"". $scores['channel']['item'][$i]['link'] ."\" title=\"". $scores['channel']['item'][$i]['description'] ."\">";
        echo $scores['channel']['item'][$i]['title'];
        echo "</a><br />";
        
        preg_match("/^[A-Z][A-Za-z]*/", $scores['channel']['item'][$i]['title'], $match);
        preg_match("/[0-9][0-9]*/", $scores['channel']['item'][$i]['title'], $match2);
        preg_match("/,.[A-Z][A-Za-z]*/", $scores['channel']['item'][$i]['title'], $match3);
        preg_match("/[0-9]*[0-9].\(F\)$/", $scores['channel']['item'][$i]['title'], $match4);
        
        $results = array();
        
        $results[$i]['TeamA'] = $match[0];
        $results[$i]['ScoreA'] = $match2[0];
        $results[$i]['TeamB'] = substr($match3[0], 2);
        $results[$i]['ScoreB'] = substr($match4[0], 0, -3);
        
        echo "
            <table border='1'>
                <tr>
                    <td>".$results[$i]['TeamA']."</td>
                    <td>".$results[$i]['ScoreA']."</td>
                </tr>
                <tr>
                    <td>".$results[$i]['TeamB']."</td>
                    <td>".$results[$i]['ScoreB']."</td>
                </tr>
            </table>
        ";
}

The table format is just so I can easily see how the data's being separated.

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.