我正在尝试打破体育比分的RSS feed
示例数据
San Diego 4 Chicago Cubs 2 Miami 2 Philadelphia 7 Boston 3 Toronto 1 Washington 3 Atlanta 1 Chicago Sox 3 Texas 1 St. Louis 6 Milwaukee 5
rss基本上给了我像San Diego 4 Chicago Cubs 2
一个stream动的string,我试图分解它,以便更好地使用。
基本上我试图首先将San Diego 4 Chicago Cubs 2
分成四个variables, $home_team
, $home_score
, $away_team
, $away_score
。
但是,显然主队可以是一个字或更多,得分可以是1个数字或3个,所以我一直在试图找出最好的正则expression式,以正确的格式拆分。
有没有人有任何想法?
更新
代码,我实际上使用这个,我拉xml mlb游戏今天,筛选出只是标记为最终含义最终得分的游戏,然后即时通讯试图从那里进一步分解..
<?php $xml = simplexml_load_file("http://feeds.feedburner.com/mpiii/mlb?format=xml"); foreach($xml->channel->item as $item){ if(preg_match('/(FINAL)/', $item->title, $matches) || preg_match('/(POSTPONED)/', $item->title, $matches)){ if(preg_match('/(POSTPONED)/', $item->title, $matches)){ continue; } $string = $item->title; $patterns = array(); $patterns[0] = '/\\(FINAL\\)/'; $patterns[1] = '/\\(POSTPONED\\)/'; $replacements = array(); $replacements[1] = ''; $replacements[0] = ''; $string = preg_replace($patterns, $replacements, $string); $keywords = preg_match("^(.*?) ([0-9]{1,3}) (.*?) ([0-9]{1,3})$", $string); echo $keywords[1]."<br/>"; } } ?>
您可以根据数字序列拆分字符串,假定团队名称不包含数字:)
$s = 'San Diego 4 Chicago Cubs 2'; list($home_team, $home_score, $away_team, $away_score) = array_filter( array_map('trim', preg_split('/\b(\d+)\b/', $s, -1, PREG_SPLIT_DELIM_CAPTURE) ), 'strlen');
$arr = array("San Diego 4 Chicago Cubs 2", "Miami 2 Philadelphia 7", "Boston 3 Toronto 1", "Washington 3 Atlanta 1", "Chicago Sox 3 Texas 1", "St. Louis 6 Milwaukee 5" ); $results = array(); foreach ($arr as $v) { $scores = preg_split("/[A-Za-z\s\.]+/", $v); $teams = preg_split("/[\d]+/", $v); $results[] = "Home: ".$teams[0]." (".$scores[1]."), Away: ".$teams[1]." (".$scores[2].")"; } foreach ($results as $v) { echo $v."<br>"; }
结果:
主场:圣地亚哥(4),客场:芝加哥小熊队(2)
主场:迈阿密(2),客场:费城(7)
主页:波士顿(3),客场:多伦多(1)
主页:华盛顿(3),客场:亚特兰大(1)
主页:Chicago Sox(3),客场:德州(1)
主场:圣路易斯(6),客场:密尔沃基(5)
你可以很明显地构造出你想要的$results
; 但解决方案的肉是正则表达式:
$scores = preg_split("/[A-Za-z\s\.]+/", $v); $teams = preg_split("/[\d]+/", $v);
也许
<?php $rssLine="San Diego 4 Chicago Cubs 2"; //add code to loop though lines if(preg_match ("/^(.*?) ([0-9]{1,3}) (.*?) ([0-9]{1,3})$/" ,$rssLine, $matches) ===1){ $home_team = $matches[1]; $home_score = $matches[2]; $away_team = $matches[3]; $away_score = $matches[4]; } else{ //log no match found } ?>
第一场是主队。 比赛2是主场比分。 比赛3是客队。 比赛4是客场比分
这可能正是你想要的:
<?php $your_input_string ="San Diego 4 Chicago Cubs 2 Miami 2 Philadelphia 7 Boston 3 Toronto 1 Washington 3 Atlanta 1 Chicago Sox 3 Texas 1 St. Louis 6 Milwaukee 5 "; $your_result = array_chunk(array_filter( array_map('trim', preg_split('/\b(\d+)\b/', $your_input_string, -1, PREG_SPLIT_DELIM_CAPTURE)), 'strlen'),4); echo '<pre>'; print_r($your_result); ?>
现场演示>>