PHP trim()関数
例
文字列の両端の文字("Hello" の "He" と "World" の "d!")を削除します:
$str = "Hello World!";
echo $str . PHP_EOL;
echo trim($str,"Hed!");
例を実行 »
定義と使い方
trim() 関数は、文字列の両端の空白文字またはその他の定義済み文字を削除します。
関連関数:
構文
trim(string,charlist)
| パラメータ | 説明 |
|---|---|
| string | 必須。チェックする文字列を指定します。 |
| charlist | 省略可能。文字列から削除する文字を指定します。このパラメータを省略した場合、次のすべての文字が削除されます:
|
技術詳細
| 戻り値: | 変更された文字列を返します。 |
|---|---|
| PHP バージョン: | 4+ |
| 変更履歴: | PHP 4.1 で、新たに追加されたのはcharlistパラメータです。 |
その他の例
例 1
文字列の両端のスペースを削除します:
$str = " Hello World! ";
echo "Without trim: " . $str;
echo "<br>";
echo "With trim: " . trim($str);
上記のコードの HTML 出力は次のとおりです(ソースコードを表示):
<!DOCTYPE html>
<html>
<body>
Without trim: Hello World! <br>With trim: Hello World!
</body>
</html>
上記のコードのブラウザ出力は次のとおりです:
Without trim: Hello World!
With trim: Hello World!
With trim: Hello World!
例を実行 »
例 2
文字列の両端の改行文字(\n)を削除します:
$str = "nnnHello World!nnn";
echo "Without trim: " . $str;
echo "<br>";
echo "With trim: " . trim($str);
上記のコードの HTML 出力は次のとおりです(ソースコードを表示):
<!DOCTYPE html>
<html>
<body>
Without trim:
Hello World!
<br>With trim: Hello World!
</body>
</html>
上記のコードのブラウザ出力は次のとおりです:
Without trim: Hello World!
With trim: Hello World!
With trim: Hello World!
例を実行 »
PHP String リファレンスマニュアル その他の拡張機能