PHP Function Reference

PHP rawurlencode() Function



The PHP rawurlencode() function encodes the given string according to RFC 3986. The function returns a string in which all non-alphanumeric characters except -_.~ have been replaced with a percent (%) sign followed by two hex digits.

From RFC 3986: A Uniform Resource Identifier (URI) is a compact sequence of characters that identifies an abstract or physical resource. This specification defines the generic URI syntax and a process for resolving URI references that might be in relative form, along with guidelines and security considerations for the use of URIs on the Internet. The URI syntax defines a grammar that is a superset of all valid URIs, allowing an implementation to parse the common components of a URI reference without knowing the scheme-specific requirements of every possible identifier.

Syntax

rawurlencode(string)

Parameters

string Required. Specify the URL to be encoded.

Return Value

Returns a string in which all non-alphanumeric characters except -_.~ have been replaced with a percent (%) sign followed by two hex digits. This is the encoding described in RFC 3986 for protecting literal characters from being interpreted as special URL delimiters, and for protecting URLs from being mangled by transmission media with character conversions (like some email systems).

Example:

The example below shows the usage of rawurlencode() function.

<?php
echo '<a href="www.alphacodingskills.com/',
  rawurlencode('an online learning portal'), '">';
?>

The output of the above code will be:

<a href="www.alphacodingskills.com/an%20online%20learning%20portal">

Example:

Consider one more example which shows how a string is encoded and decoded.

<?php
$str1 = "AlphaCodingSkills an online learning portal";
$encoded_str1 = rawurlencode($str1);

echo "The string is: $str1 \n";
echo "Encoded string: $encoded_str1 \n";

$str2 = "AlphaCodingSkills%20an%20online%20learning%20portal";
$decoded_str2 = rawurldecode($str2);

echo "\nThe string is: $str2 \n";
echo "Decoded string: $decoded_str2 \n";
?>

The output of the above code will be:

The string is: AlphaCodingSkills an online learning portal 
Encoded string: AlphaCodingSkills%20an%20online%20learning%20portal 

The string is: AlphaCodingSkills%20an%20online%20learning%20portal 
Decoded string: AlphaCodingSkills an online learning portal 

❮ PHP URLs Reference