先日作ったDSi専用のページを作ったんですが、正規表現の勉強になったのでメモエントリ。
アンカータグ、hrefアトリビュート内のURLを抜く正規表現や、strip_tagsを補完するものなどがあります。
アンカータグ、hrefアトリビュート内のURLを抜く正規表現や、strip_tagsを補完するものなどがあります。
あとはyahoo pipesで出力されるphpのserializeとunserializeの方法を覚えました。ちょっと良く解ってないかもしれないけど、インスタンス化されたクラスをリテラルで表せるという感じでしょうか。
ちなみに、yahoo pipesはこんな感じで作った。始めは全文表示(サンプル)をしながらyahoo pipesですべてまかなおうかと思ったんですけど、単一ページに沢山詰め込むより、ページごとのサイズが小さい方がなにかとパフォーマンスが良いみたいなのでこうしました。
<?php
function append_link( $html, $appendix, $host ) {
// /news/index.html -> http://hogehoge.com/news/index.html
$html = preg_replace( '/(<a\s[^>]*?href\s*=["\'])(?!http)/i', '$1' . $host, $html );
// http://hogehoge.com -> http://mojalog.com/dsi.php?http://hogehoge.com
return preg_replace( '/(<a\s[^>]*?href\s*=["\']?)/i', "$1$appendix", $html );
}
function removeTag( $input, $validTags = '' )
{
// remove script, stype, CData
$regexList = array(
'/<script[^>]*?>.*?<\/script>/si',
'/<style[^>]*?>.*?<\/style>/siU',
'/<![\s\S]*?--[ \t\n\r]*>/'
);
$input = preg_replace( $regexList, '', $input );
// remove invalid tags.
$regex = '#\s*<(/?\w+)\s+(?:on\w+\s*=\s*(["\'\s])?.+?\(\1?.+?\1?\);?\1?|style=["\'].+?["\'])\s*>#is';
return preg_replace( $regex, '<${1}>', strip_tags( $input, $validTags ) );
}
// ---------------------------------------------------------------------------
// rendering.
// ---------------------------------------------------------------------------
$qry = $_SERVER[ "QUERY_STRING" ];
$selfPage = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER["PHP_SELF"];
if( !preg_match( '/^(https?|ftp)(:\/\/[-_.!~*\'()a-zA-Z0-9;\/?:\@&=+\$,%#]+)$/', $qry ) ){
$req = "http://pipes.yahoo.com/pipes/pipe.run?_id=150f5f5822e1009b5fd7f90fb46a1397&_render=php";
$serialized = file_get_contents( $req );
$list = unserialize( $serialized );
$size = count( $list["value"]["items"] );
echo '<a href="' . $selfPage . '">home</a><hr/>';
for( $idx = 0; $idx < $size; $idx++ ){
$titleStr = $list["value"]["items"][$idx]["title"];
$linkStr = $list["value"]["items"][$idx]["link"];
$descriptionStr = $list["value"]["items"][$idx]["description"];
echo '<a href="' . $selfPage . '?' . $linkStr . '">' . $titleStr . '</a><img src="http://b.hatena.ne.jp/entry/image/small/' . $linkStr . '" /><br /><br />';
echo $descriptionStr . "<br /><hr />";
}
echo '<a href="' . $selfPage . '">home</a>';
}
else {
$hostname = preg_replace( "/(https?:\/\/)([^\/]+)(\/.*$)?/i", "$1$2", $qry ) . '/';
if( !getimagesize( $qry ) ){
$targetContent = mb_convert_encoding( file_get_contents( $qry ),'UTF-8', 'auto' );
$content = removeTag( $targetContent, "<a><br><b><h1><h2><h3><h4><i><p><strong><u><img>" ) . "<br />";
echo '<a href="' . $selfPage . '">home</a><hr/>' . append_link( $content, $selfPage . '?', $hostname ) . '<hr/><a href="' . $selfPage . '">home</a>';
}
else {
echo '<img src="' . $qry . '" />';
}
}
?>










