テキスト内にある短縮されたURLを抜き出して、そのURLを展開した結果のページタイトルを取得剃る方法です。
PHPというか試したのはCakePHPですが、基本的には同じはず。
以下がサンプル。
httpしか取得していないので正規表現は適当に変更してください。
タイトル取得の時に、先頭に改行が入っているケースがあるので、ltrimしてます。
[php]
function main() {
$txt = ‘サンプル http://test.com サンプル’;
preg_match_all("/http:\/\/[a-z0-9\/\-_\.]+/i",$txt,$match);
foreach($match[0] as $match_url){
$URL = $this->getSquare($short_url = $match_url);
$data[‘favo_title’] = $this->getPageTitle($URL);
}
}
// URL取得
public function getSquare($short_url){
$h = get_headers($short_url,true);
if(isset($h[‘Location’])){
$long_url = $h[‘Location’];
if(is_array($long_url)){
$long_url = end($long_url);
}
}
return $long_url;
}
// タイトル取得
function getPageTitle( $url ) {
$html = file_get_contents($url);
$html = mb_convert_encoding($html, mb_internal_encoding(), ‘auto’ );
if ( preg_match( "/<title>(.*?)<\/title>/is", $html, $matches) ) {
return ltrim($matches[1]);
} else {
return false;
}
}
[/php]
file_get_contentsは遅いね。
もっと良いやり方があったら教えて頂けると幸いです。