PHP - strlen() 函式



PHP 的 strlen() 函式用於獲取給定字串的長度。“長度”指的是字串包含的 **位元組** 數,而不是字元數。

如果給定的字串是 **空** 字串(不包含任何字元或空格),則此函式將返回“零”。如果字串為空但包含空格,它將計算每個空格為一個位元組並返回字串的長度。

語法

以下是 PHP strlen() 函式的語法:

strlen(string $str): int

引數

以下是此函式的引數:

  • string: 將計算其長度的輸入字串。

返回值

此函式返回字串的長度。

示例 1

下面的程式演示了 PHP strlen() 函式的用法。它返回給定字串的長度:

<?php
   $str = "Hello from TP";
   echo "The given string: $str";
   echo "\nThe length of the given string: ";
   #using strlen() function
   echo strlen($str);
?>

輸出

以上程式產生以下輸出:

The given string: Hello from TP
The length of the given string: 13

示例 2

如果字串為空(不包含空格),PHP strlen() 函式將返回 0 作為字串長度:

<?php
   $str = "";
   echo "The given string: '$str'";
   echo "\nThe length of the given string: ";
   #using strlen() function
   echo strlen($str);
?>

輸出

以下是以上程式的輸出:

The given string:''
The length of the given string: 0

示例 3

如果給定的字串為空(但包含空格),PHP strlen() 函式將計算每個空格為一個位元組並返回字串的長度:

<?php
   $str = "    ";
   echo "The given string: '$str'";
   echo "\nThe length of the given string: ";
   #using strlen() function
   echo strlen($str);
?>

輸出

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

The given string: '    '
The length of the given string: 4
php_function_reference.htm
廣告