Created
July 3, 2012 14:29
-
-
Save mitaken/3040056 to your computer and use it in GitHub Desktop.
絶対URLをもとに相対URLから絶対URLを生成
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| /** | |
| * 絶対パスの取得 | |
| * | |
| * @param string $base | |
| * @param string $absolute | |
| * @return string | |
| */ | |
| function getHttpPath($base, $absolute) | |
| { | |
| $uri = Zend_Uri_Http::fromString($base); | |
| $absolute = str_replace(' ', '%20', trim($absolute)); | |
| if (strpos($absolute, '//') === 0) { // //example.com -> http://example.com | |
| $absolute = $uri->getScheme() . ':' . $absolute; | |
| } | |
| if (strpos($absolute, '/') === 0) { // /path -> http://example.com/path | |
| $absolute = $uri->getScheme() . '://' . $uri->getHost() . $absolute; | |
| } | |
| if (Zend_Uri_Http::check($absolute) || preg_match('/^(javascript|mailto|device|tel):/i', $absolute)) { | |
| return $absolute; | |
| } | |
| if (($pos = strpos($absolute, '#')) !== false) { // #fragment | |
| $uri->setFragment(substr($absolute, $pos + 1)); | |
| $absolute = substr($absolute, 0, $pos); | |
| } | |
| list($absolute, $query) = explode('?', $absolute . '?'); // ?query | |
| $uri->setQuery($query); | |
| $path = str_replace('//', '/', $uri->getPath()); // /foo//bar/hoge -> /foo/bar/hoge | |
| if (strrpos($path, '/') !== 0) { // exists /foo/bar/hoge | |
| $path = explode('/', substr($path, 1, strrpos($path, '/') - 1)); // /foo/bar/hoge -> array('foo', 'bar') | |
| } else { | |
| $path = array(); | |
| } | |
| $list = explode('/', $absolute); | |
| foreach ($list as $part) { | |
| if (in_array($part, array('', '.'))) { | |
| continue; | |
| } | |
| if (preg_match('/^\.+$/', $part)) { | |
| array_pop($path); | |
| } else { | |
| $path[] = $part; | |
| } | |
| } | |
| $uri->setPath('/' . implode('/', $path) . ((count($path) && substr($absolute, -1) === '/') ? '/' : '')); | |
| return $uri->getUri(); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment