IdnaEncoder::to_ascii( string $text ): string

In this article

Convert a UTF-8 text string to an ASCII string using Punycode

Parameters

$textstringrequired
ASCII or UTF-8 string (max length 64 characters)

Return

string ASCII string

Source

public static function to_ascii($text) {
	// Step 1: Check if the text is already ASCII
	if (self::is_ascii($text)) {
		// Skip to step 7
		if (strlen($text) < self::MAX_LENGTH) {
			return $text;
		}

		throw new Exception('Provided string is too long', 'idna.provided_too_long', $text);
	}

	// Step 2: nameprep
	$text = self::nameprep($text);

	// Step 3: UseSTD3ASCIIRules is false, continue
	// Step 4: Check if it's ASCII now
	if (self::is_ascii($text)) {
		// Skip to step 7
		/*
		 * As the `nameprep()` method returns the original string, this code will never be reached until
		 * that method is properly implemented.
		 */
		// @codeCoverageIgnoreStart
		if (strlen($text) < self::MAX_LENGTH) {
			return $text;
		}

		throw new Exception('Prepared string is too long', 'idna.prepared_too_long', $text);
		// @codeCoverageIgnoreEnd
	}

	// Step 5: Check ACE prefix
	if (strpos($text, self::ACE_PREFIX) === 0) {
		throw new Exception('Provided string begins with ACE prefix', 'idna.provided_is_prefixed', $text);
	}

	// Step 6: Encode with Punycode
	$text = self::punycode_encode($text);

	// Step 7: Prepend ACE prefix
	$text = self::ACE_PREFIX . $text;

	// Step 8: Check size
	if (strlen($text) < self::MAX_LENGTH) {
		return $text;
	}

	throw new Exception('Encoded string is too long', 'idna.encoded_too_long', $text);
}

User Contributed Notes

You must log in before being able to contribute a note or feedback.