php ltrimで文字列の先頭から空白または指定した文字列を削除する

  • 作成日 2021.10.15
  • 更新日 2022.05.22
  • php
php ltrimで文字列の先頭から空白または指定した文字列を削除する

phpで、ltrimを使用して、文字列の先頭から空白または指定した文字列を削除するサンプルコードを記述してます。phpのバージョンは8.0です。

環境

  • OS  CentOS Linux release 8.0.1905 (Core)
  • php 8.0.0
  • nginx 1.14.1

ltrim使い方

ltrimを使用すれば、文字列の先頭から空白または指定した文字列を削除することが可能です。

ltrim(文字列,[削除したい文字]);
// 第二引数は、指定しない場合は空白や改行やタブが削除されます

以下は、文字列の先頭から空白と改行とタブを削除するサンプルコードとなります。

<?php

$str = "  
\t\thello world";

$result = ltrim($str);

var_dump($result); // string(11) "hello world

全角空白文字は削除されません。

<?php

$str = " hello world";

$result = ltrim($str);

var_dump($result); // string(14) " hello world"

第二引数に削除したい文字を指定した場合は、指定した文字が削除されます。

<?php

$str = "hello world";

$result = ltrim($str,"he");

var_dump($result); // string(9) "llo world"

第二引数に「hel」と指定した場合は、「hell」まで削除されます。

<?php

$str = "hello world";

$result = ltrim($str,"hel");

var_dump($result); // string(7) "o world"

また、文字列の順序を変えても結果は同じになります。

<?php

$str = "hello world";

$result = ltrim($str,"ehl");

var_dump($result); // string(7) "o world"