tmallen Posted April 6, 2008 Share Posted April 6, 2008 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? Quote Link to comment Share on other sites More sharing options...
tmallen Posted April 6, 2008 Author Share Posted April 6, 2008 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. Quote Link to comment Share on other sites More sharing options...
effigy Posted April 7, 2008 Share Posted April 7, 2008 Splits on a comma with trailing space, or space with a trailing digit or opening paren. <pre> <?php $str = 'Hornets 118, Knicks 110 (F)'; $pieces = preg_split('/(?:,\s+|\s+(?=\d+|\())/', $str); print_r($pieces); ?> </pre> Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.