1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

PHPでURLの文字列操作

Last updated at Posted at 2018-03-28

スクレイピング周りの作業をしていて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'];
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?