2013-05-30 96 views
0

此问题已被多次询问,但我没有找到适合我需求的工作解决方案。PHP正则表达式匹配字符串,但排除某个单词

我创建了一个函数来检查在谷歌的Ajax API输出的URL: https://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=site%3Awww.bierdopje.com%2Fusers%2F+%22Gebruikersprofiel+van+%22+Stevo

我想从输出中排除的“轨迹”一词。因此,如果字符串包含该字词,则跳过整个字符串。

这是我创建至今的功能:我创建了一个示例,使

function getUrls($data) 
{ 
    $regex = '/https?\:\/\/www.bierdopje.com[^\" ]+/i'; 
    preg_match_all($regex, $data, $matches); 
    return ($matches[0]); 
} 

$urls = getUrls($data); 
$filteredurls = array_unique($urls); 

清楚我的意思正是:
http://rubular.com/r/1U9YfxdQoU

在样本可以看到4从中选择的字符串我只需要上面的2个字符串。 我该如何做到这一点?

+2

你为什么用正则表达式解析JSON会让你的生活变得糟糕透顶? –

+0

你的代码很好。你面临什么问题? – Rikesh

+0

@Rikesh,问题是它有4场比赛而不是2场比赛,我不知道我会如何“不匹配”过去的两场比赛。查看我的示例以了解我的意思。 – Tom

回答

0
function getUrls($data) 
{ 
    $regex = '@"(https?://www\\.bierdopje\\.com[^"]*+(?<!/profile))"@'; 
    return preg_match_all($regex, $data, $matches) ? 
     array_unique($matches[1]) : array(); 
} 

$urls = getUrls($data); 

结果:http://ideone.com/dblvpA

VS json_decodehttp://ideone.com/O8ZixJ

但是一般您应该使用json_decode

+1

不仅仅是'一般',正则表达式解决方案会在Google输出中发生更改,URL被添加或删除,或者示例输出包含URL时突然崩溃。 –

+0

谢谢!代码对我来说工作得很好。我还要感谢Niels提供的关于如何正确使用json_decode的代码。这也很方便。 – Tom

1

请勿使用正则表达式来解析JSON数据。你想要做的是解析JSON并循环找到正确的匹配元素。

示例代码:

$input = file_get_contents('https://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=site%3Awww.bierdopje.com%2Fusers%2F+%22Gebruikersprofiel+van+%22+Stevo'); 
$parsed = json_decode($input); 

$cnt = 0; 
foreach($parsed->responseData->results as $response) 
{ 
    // Skip strings with 'profile' in there 
    if(strpos($response->url, 'profile') !== false) 
     continue; 

    echo "Result ".++$cnt."\n\n"; 
    echo 'URL: '.$response->url."\n"; 
    echo 'Shown: '.$response->visibleUrl."\n"; 
    echo 'Cache: '.$response->cacheUrl."\n\n\n"; 
} 

Sample on CodePad(因为它不支持加载外部文件中的字符串被内联有)

+0

谢谢你的代码。这会很方便。我不能给你+1,但是一旦我收到适量的代表。我会稍后再做(如果可能的话)。 – Tom

相关问题