LoginSignup
3
3

More than 5 years have passed since last update.

PHPでURL文字列を解析・変更する(pear/Net_URL2)

Last updated at Posted at 2016-12-09

やりたいこと

PHPでURL文字列のポートとかパスとかを書き換えたい。

たとえば、 http://localhost/hoge/moge というURLから、
http://localhost:8888/hoge/moge を作ったりだとか、
http://localhost/uge を作ったりしたい。

正規表現でぐりぐり弄っても良かったけれど……
可読性の低いコードになりそうだったので、今回はライブラリを探して利用してみることにした。

使ったもの

pear/Net_URL2
https://github.com/pear/Net_URL2

Class for parsing and handling URL. Provides parsing of URLs into their constituent parts (scheme, host, path etc.), URL generation, and resolving of relative URLs.

スキーム、ホスト、パスなどの解析を行ったり、組み立てたりできる、便利そうなやつ。

使い方

インストール

Composerにも置かれていたので、以下のコマンドでインストールした。

$ composer require pear/net_url2

ソースコード

url.php
// ライブラリの読み込み
require('vendor/autoload.php');


// 元となるURL文字列からインスタンスを生成
$url = new Net_URL2('http://localhost/hoge/moge');

// 情報を書き換える
$url->setPort(8888);
$url->setPath('/uge');

// http://localhost:8888/uge
echo $url->getURL();

参考

3
3
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
3
3