Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationEventAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
1
Help us understand the problem. What are the problem?

More than 3 years have passed since last update.

PHPでURLの文字列操作

スクレイピング周りの作業をしていてURLの文字列操作が面倒で調べてみたところ、
parse_urlがというのを知りました、pathinfoみたいで便利でした。

ルートURLを取得する

$url = 'http://example.com/test/test.txt';
$url_info = parse_url($url);
$root_url = $url_info['scheme'].'://'.$url_info['host'];

var_dump($root_url);
var_dump($url_info);
string(18) "http://example.com"
array(3) {
  ["scheme"]=>
  string(4) "http"
  ["host"]=>
  string(11) "example.com"
  ["path"]=>
  string(14) "/test/test.txt"
}

ベースURLを取得する

こっちはpathinfoを使用

$url = 'http://example.com/test/test.txt';
$url_info = pathinfo($url);
$base_url = $url_info['dirname'];

var_dump($base_url);
var_dump($url_info);
string(23) "http://example.com/test"
array(4) {
  ["dirname"]=> string(23) "http://example.com/test"
  ["basename"]=> string(8) "test.txt"
  ["extension"]=> string(3) "txt"
  ["filename"]=> string(4) "test"
}

/で終わる場合

$url = 'http://example.com/test/';
$url_info = pathinfo($url);
$base_url = $url_info['dirname'];

var_dump($base_url);
var_dump($url_info);
string(18) "http://example.com"
array(3) {
  ["dirname"]=>
  string(18) "http://example.com"
  ["basename"]=>
  string(4) "test"
  ["filename"]=>
  string(4) "test"
}

この場合は$urlをそのまま使うこと

$base_url = (preg_match('/\/$/u', $url) === 1) ? $url : pathinfo($url)['dirname'];
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
1
Help us understand the problem. What are the problem?