PHP取远程文件绝对路径

写采集程序的时候, 需要根据 当前页 和 下一页 计算出 下一页的绝对地址,写了一个常用的转换函数, 方便以后采集转换地址。

第一个参数是相对页面的url, 第二个参数是采集到的下一页地址, 然后就会返回一个带有http的下一个地址。

  1. <?php
  2. function get_abs_url($url, $filename) {
  3. // 如果是http|https|ftp|//开头的
  4. if (preg_match('/^[a-zA-Z]*\:?\/\//', $filename)) {
  5. return $filename;
  6. }
  7. // 如果是 /common/css/index.css
  8. if (substr($filename, 0, 1) == '/') {
  9. preg_match('/^[^\/]*\/\/[^\/]+/', $url, $domain);
  10. return $domain[0] . $filename;
  11. }
  12. // 去掉问号和#号后面的字符, 删除文件名, 只保留目录
  13. $url = strstr($url, '?', true) ? strstr($url, '?', true) :
  14. (strstr($url, '#', true) ? strstr($url, '#', true) : $url);
  15. $url = preg_replace('/[^\/]*$/', '', $url);
  16. // 如果是 ../../common/css/index.css
  17. if (substr($filename, 0, 3) == '../') {
  18. $filename = $url . $filename;
  19. while (preg_match('/[^\/\.]+\/\.\.\//', $filename)) {
  20. $filename = preg_replace('/[^\/\.]+\/\.\.\//', '', $filename);
  21. }
  22. return $filename;
  23. }
  24. // 如果是 ./common/css/index.css
  25. if (substr($filename, 0, 2) == './') {
  26. return str_replace('/./', '/', $url . $filename);
  27. }
  28. return $url . $filename;
  29. }

实现了下面几种模式:

  1. echo get_abs_url('http://www.baidu.com/blog/shuai/article/1.html?php=php#hello', '../../../common/css.css');
  2. echo '<br />';
  3. echo get_abs_url('http://www.baidu.com/blog/shuai/article/1.html?php=php#hello', 'http://static.baidu.com/common/css.css');
  4. echo '<br />';
  5. echo get_abs_url('http://www.baidu.com/blog/shuai/article/1.html?php=php#hello', '/common/css.css');
  6. echo '<br />';
  7. echo get_abs_url('http://www.baidu.com/blog/shuai/article/1.html?php=php#hello', './common/css.css');
  8. echo '<br />';
  9. echo get_abs_url('http://www.baidu.com/blog/shuai/article/1.html?php=php#hello', 'css.css');
文章不错, 赏你二两银子

如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续努力!