概要
headerにlocationかlinkがあればurlだけにして返します。
preg_match_all()ってサブパターンも取れた気がするんですが、どうやってやってるのかよくわかりませんでした。
コード
$link = 'https://noarts.net/archives/453'; $header_default = get_headers( $link ); $default_link = pick_header_link($header_default); var_dump($default_link); function pick_header_link($target_header){ $target_text = implode( "\n", $target_header ); $header_link = ''; // headerがlinkのもの $preg1 = '/Link:\s*<[^<>]*>;\s*rel=shortlink/i'; preg_match_all( $preg1, $target_text, $preg_link ); if(!empty($preg_link[0][0])){ $header_link = $preg_link[0][0]; } // headerがlocationのもの $preg2 = '/Location:\s*[^\n]*/i'; preg_match_all( $preg2, $target_text, $preg_location ); if(!empty($preg_location[0][0])){ $header_link = $preg_location[0][0]; } if(!empty($header_link)){ // URLだけにする $preg3 = '/https?:[^<>\n]*/i'; preg_match_all( $preg3, $header_link, $h_link ); if(count($h_link) === 1){ $header_link = $h_link[0][0]; } } return $header_link; }
実行例
/var/www/html/test.php:12:string ‘https://noarts.net/?p=453’ (length=25)