PHP - rawurlencode() 函式



PHP URL rawurlencode() 函式用於根據 RFC 3986 編碼字串。這意味著它替換 URL 中的特殊字元。這有助於使 URL 安全地透過網際網路傳輸。

語法

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

string rawurlencode(string $str)

引數

此函式接受 $str 引數,它是需要編碼的輸入字串。

返回值

rawurlencode() 函式返回編碼後的字串,其中所有特殊字元都替換為其百分比編碼的值。

PHP 版本

rawurlencode() 函式首次在 PHP 4的核心版本中引入,在 PHP 5、PHP 7 和 PHP 8 中繼續輕鬆執行。

示例 1

這是 PHP URL rawurlencode() 函式對包含空格和特殊字元的簡單字串進行編碼的基本示例。

在此示例中,感嘆號和空格將替換為其對應的編碼字元。

<?php
   // Mention the string here
   $str = "Hello World!";
   $encodedString = rawurlencode($str);
   echo $encodedString;
?>

輸出

以上程式碼將產生類似這樣的結果:

Hello%20World%21

示例 2

現在我們將嘗試使用 rawurlencode() 函式並對 URL 路徑進行編碼以使其安全。

<?php
   // Mention URL path here
   $urlPath = "/PHP/PhpProjects/filename.html";
   $encodedPath = rawurlencode($urlPath);
   echo $encodedPath; 
?> 

輸出

執行上述程式後,它將生成以下輸出:

%2FPHP%2FPhpProjects%2Ffilename.html

示例 3

現在,以下程式碼使用 rawurlencode() 函式對包含不同特殊字元的查詢字串進行編碼。

<?php
   // Mention string here
   $str = "name=Amit Sharma&age=33";
   $encodedQuery = rawurlencode($str);
   echo $encodedQuery; 
?> 

輸出

這將建立以下輸出:

name%3DAmit%20Sharma%26age%3D33

示例 4

在下面的示例中,我們使用 rawurlencode() 函式對整個 URL 進行編碼。

<?php
   // Mention URL path here
   $url = "https://tutorialspoint.tw/search?q=hello world&lang=en";
   $encodedURL = rawurlencode($url);
   echo $encodedURL; 
?> 

輸出

執行上述程式後,將產生以下輸出:

https%3A%2F%2Fwww.tutorialspoint.com%2Fsearch%3Fq%3Dhello%20world%26lang%3Den%

示例 5

此示例顯示如何建立具有特殊字元的動態路徑的 URL,因此使用 rawurlencode() 函式將對特殊字元進行編碼。

<?php
   // Mention URL path here
   echo '<a href="https://tutorialspoint.tw/department_list_script/',
    rawurlencode('quality tutorials and courses'), '">';
?>

輸出

執行程式後,我們將得到以下輸出:

<a href="https://tutorialspoint.tw/department_list_script/quality%20tutorials%20and%20courses">   
php_function_reference.htm
廣告