这个问题已被多次询问,但我没有找到满足我需求的可行解决方案。
我创建了一个函数来检查Google Ajax API输出上的网址: 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个字符串。 我怎么能做到这一点?
答案 0 :(得分: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 (因为它不支持加载外部文件,所以在那里内联字符串)
答案 1 :(得分: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);
vs json_decode
:http://ideone.com/O8ZixJ
但一般你应该使用json_decode
。