encodeURIComponent (function)

Last updated: Mon, Apr 17, 2023 8:54 am
Return to Knowledgebase

Purpose

Used to encode a string of text to be used in a URL, where certain characters may have special meaning and need to be encoded for the URL to be valid.

Location

users/helpers/us_helpers.php

Parameters

# Parameter Data Type Required Description
1 $str string Yes Represents the text to be encoded for use in a URL.

Returns

Data Type Description of Returned Data
string Represents the encoded version of the input string.

Further Documentation:

The encodeURIComponent() function appears to be a custom implementation of the encodeURIComponent() method in JavaScript. This function is used to encode a string of text to be used in a URL, where certain characters may have special meaning and need to be encoded for the URL to be valid.

Here's a breakdown of how the function works:

$revert = ['%21' => '!', '%2A' => '*', '%27' => "'", '%28' => '(', '%29' => ')']; - This line defines an array of characters that need to be replaced in the URL. These characters include !, *, ', (, and ), which are replaced with their corresponding URL-encoded values.

return strtr(rawurlencode($str), $revert); - This line uses the rawurlencode() function to encode the string in the URL format, and then replaces the characters in the $revert array using the strtr() function. The resulting encoded string is returned.

Here's an example of how you might use this function in a PHP script:

// Encode a string for use in a URL
$encodedStr = encodeURIComponent('Hello, World!');

// Do something with the encoded string
echo $encodedStr;

Assuming that the encodeURIComponent() function is defined in a file that has been included in the script, this code encodes the string "Hello, World!" for use in a URL and prints the encoded string to the output. The resulting output would be "Hello%2C%20World%21", which is the URL-encoded version of the input string.