PHP - trim() 函式



PHP 的 trim() 函式用於從給定字串的“開頭”和“結尾”刪除空格和其他字元。

它接受一個可選的第二個引數。如果省略此引數,它將從兩端刪除以下字元

  • " " − 普通空格。
  • \t − 製表符。
  • \n − 換行符。
  • \r − 回車符。
  • \0 − NUL 型別。
  • \v − 垂直製表符。

注意:此函式僅刪除字串兩端開頭的和結尾的空格和其他指定的字元。它不會影響字串中間的任何空格或其他字元。

語法

以下是 PHP trim() 函式的語法 −

trim(string $str, string $charlist = " \n\r\t\v\x00"): string

引數

此函式接受兩個引數,如下所述 −

  • string − 要從中刪除空格和字元的原始字串。
  • charlist (可選) − 您要從原始字串 (string) 中刪除的字串或字元列表。

返回值

此函式返回一個字串,其中已從字串的開頭和結尾刪除空格和其他指定的字元。

示例 1:從兩端刪除空格

以下是 PHP trim() 函式的基本示例。它從兩端刪除空格 −

<?php
   $str = " Tutorials point "; 
   echo "The given string: '$str'";
   echo "\nThe modified string (after removing white spaces): ";
   echo "'".trim($str)."'";
?>

輸出

以上程式產生以下輸出 −

The given string: ' Tutorials point '
The modified string (after removing white spaces): 'Tutorials point'

示例 2:刪除其他指定的字元

這是使用 PHP trim() 函式的另一個示例。此函式用於從字串“I Love PHP! Language”中刪除指定的字元“Language” −

<?php
   $str = "I Love PHP! Language"; 
   echo "The given string: '$str'";
   $charslist = "Language";
   echo "\nThe other characters need to be removed: '$charslist'";
   echo "\nThe modified string: ";
   echo trim($str, $charslist);
?>

輸出

執行以上程式後,將顯示以下輸出 −

The given string: 'I Love PHP! Language'
The other characters need to be removed: 'Language'
The modified string: I Love PHP!

示例 3:刪除空格和其他字元

在下面的示例中,我們使用 PHP trim() 函式刪除空格以及其他字元(即 '!')從給定字串“ !!!Hello World!!! ”的兩端 −

<?php
   $str = " !!!Hello World!!! ";
   echo "The given string: '$str'";
   $charslist = " !";
   echo "\nThe other characters need to be removed: '$charslist'";
   echo "\nThe modified string: ";
   #using trim() function
   echo "'".trim($str, $charslist)."'";
?>

輸出

以下是以上程式的輸出 −

The given string: ' !!!Hello World!!! '
The other characters need to be removed: ' !'
The modified string: 'Hello World'
php_function_reference.htm
廣告