0

我正在尝试使用 RegEx 删除以下数据:

mlb_s_left1=Baltimore 3   ^NY Yankees 12 (FINAL)&mlb_s_right1_1=W: Hughes L: Britton&mlb_s_right1_count=1&mlb_s_url1=http://sports.espn.go.com/mlb/boxscore?gameId=320801110&mlb_s_left2=^Chicago Sox 3   Minnesota 2 (FINAL)&mlb_s_right2_1=W: Peavy L: Diamond S: Reed&mlb_s_right2_count=1&mlb_s_url2=http://sports.espn.go.com/mlb/boxscore?gameId=320801109

我希望按主队(第一城市)、主场比分(第一位)、客队(第二城市)、客场比分(第二位)以及比赛的位置(括号内)来划分。这是我目前拥有的正则表达式,但我感觉非常错误。

preg_match_all('/mlb_s_left[0-9]=(?P<hometeam>.*?) (?P<homescore>.*?)   (?P<awayteam>.*?) (?P<awayscore>.*?)\((?P<time>.*?)\)/', $content, $matches);

我将不胜感激任何帮助。

4

2 回答 2

2

这样的事情应该让你接近。

preg_match_all('/mlb_s_left\d+=(?P<hometeam>\D+)\s+(?P<homescore>\d+)\s+(?P<awayteam>\D+)\s+(?P<awayscore>\d+)\s*\((?P<time>[^)]+)\)/',
    $content, $matches);

请注意,\d匹配任何数字,并\D匹配任何数字。

[^)]+匹配一个或多个非闭合括号字符;\s+匹配一个或多个空白字符,并\s*匹配零个或多个空白字符。

如果你有一个带有数字的城市名称,这将不会很好地工作,如果你有一个很大的字符串,它可能会挂在某个地方;您可能会考虑将其拆分并更零碎地匹配。

一般来说,我会避免.*?作为模式匹配,因为它基本上匹配几乎任何东西。根据您对数据的了解,您的正则表达式最好尽可能具体。

于 2012-08-02T02:52:07.550 回答
2

我在 php 5.4.5 中测试了以下代码片段:

    <?php
$foo = 'mlb_s_left1=Baltimore 3   ^NY Yankees 12 (FINAL)&mlb_s_right1_1=W: Hughes L: Britton&mlb_s_right1_count=1&mlb_s_url1=http://sports.espn.go.com/mlb/boxscore?gameId=320801110&mlb_s_left2=^Chicago Sox 3   Minnesota 2 (FINAL)&mlb_s_right2_1=W: Peavy L: Diamond S: Reed&mlb_s_right2_count=1&mlb_s_url2=http://sports.espn.go.com/mlb/boxscore?gameId=320801109';
preg_match_all('/mlb_s_left\d=\^?(?P<hometeam>[a-zA-Z]+(?:\s+[a-zA-Z]+)*)\s+(?P<homescore>\d+)\s+\^?(?P<awayteam>[a-zA-Z]+(?:\s+[a-zA-Z]+)*)\s+(?P<awayscore>\d+)\s+\((?P<time>\w+)\)/', $foo, $matches, PREG_SET_ORDER);

print_r($matches);

?>

输出:

    Array
(
    [0] => Array
        (
            [0] => mlb_s_left1=Baltimore 3   ^NY Yankees 12 (FINAL)
            [hometeam] => Baltimore
            [1] => Baltimore
            [homescore] => 3
            [2] => 3
            [awayteam] => NY Yankees
            [3] => NY Yankees
            [awayscore] => 12
            [4] => 12
            [time] => FINAL
            [5] => FINAL
        )

    [1] => Array
        (
            [0] => mlb_s_left2=^Chicago Sox 3   Minnesota 2 (FINAL)
            [hometeam] => Chicago Sox
            [1] => Chicago Sox
            [homescore] => 3
            [2] => 3
            [awayteam] => Minnesota
            [3] => Minnesota
            [awayscore] => 2
            [4] => 2
            [time] => FINAL
            [5] => FINAL
        )

)
于 2012-08-02T03:07:04.513 回答