PHPのtrim()関数
例
文字列の両側から文字を削除します(「Hello」の「He」と「World」の「d!」):
<?php
$str = "Hello World!";
echo $str . "<br>";
echo trim($str,"Hed!");
?>
定義と使用法
Trim()関数は、文字列の両側から空白やその他の事前定義された文字を削除します。
関連機能:
構文
trim(string,charlist)
パラメータ値
Parameter | Description |
---|---|
string | Required. Specifies the string to check |
charlist | Optional. Specifies which characters to remove from the string. If omitted, all of the following characters are removed:
|
技術的な詳細
戻り値: | 変更された文字列を返します |
---|---|
PHPバージョン: | 4歳以上 |
変更ログ: | charlistパラメータはPHP4.1で追加されました |
その他の例
例
文字列の両側から空白を削除します。
<?php
$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!
例
文字列の両側から改行(\ n)を削除します。
<?php
$str = "\n\n\nHello World!\n\n\n";
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!
❮PHP文字列リファレンス