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 3 years have passed since last update.

【Laravel】ドット区切りの文字列から一部を取得する

Last updated at Posted at 2020-03-13

example.co.jp という文字列から example を取り出したいとき

$url = 'example.co.jp';

// 最初のドットの位置
$pos = strpos($url, '.');

// 先頭からドットまでの文字列を取得
$name = substr($url, 0, $pos);

var_dump($name); // 'example'


// 1行で書く場合
var_dump(substr($url, 0, strpos($url, '.'))); // 'example'

とかしなくても↓でいける

$url = 'example.co.jp';

var_dump(Str::before($url, '.')) // 'example'
$url = 'example.co.jp';

var_dump(Str::after($url, '.')) // 'co.jp'

[2020/05/10 追記]

afterLast でTLDを取得できる

$url = 'example.co.jp';

var_dump(Str::afterLast($url, '.')) // 'jp'

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?