1
0

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 1 year has passed since last update.

可変長引数でディレクトリ、ファイル名を結合する

Last updated at Posted at 2022-04-29

phpでディレクトリを複数結合してパスを取得するfunctionを作りました。
引数の前後のスラッシュを意識する必要はありません。

	function __getPath() {
		return preg_replace('/(?<!:)\/+/', '/', implode('/', array_filter(array_map('trim', func_get_args()), 'strlen')));
	}

使用例

	echo __getPath('/', '/images/common/', 'logo', 'thumb_logo_bsquare.svg');

結果

	/images/common/logo/thumb_logo_bsquare.svg

引数にnullやスペース、スラッシュが複数入っていても大丈夫です。

	echo __getPath( null, '', '  ', '///images/common/', 'logo', 'thumb_logo_bsquare.svg')

結果

	/images/common/logo/thumb_logo_bsquare.svg

先頭にスラッシュがない場合は相対パスとして出力されます。

	echo __getPath('', 'images/common/', 'logo', 'thumb_logo_bsquare.svg')

結果

	images/common/logo/thumb_logo_bsquare.svg

http(s)から始まる場合

	echo __getPath('https://www.sample.com/', 'images/common/', 'logo', 'thumb_logo_bsquare.svg')

結果

	https://www.sample.com/images/common/logo/thumb_logo_bsquare.svg

以上です。

1
0
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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?