antispambot()WP 0.71

Converts email addresses characters to HTML entities to stop spam-bots from parsing your email.

Typically this will randomly replace characters from the email address with HTML character references; however, when the hex encoding parameter is set, some characters will also be represented in their percent-encoded form.

Because this function is randomized, the outputs for any given input may differ between calls. This helps diversify the ways the email addresses are obscured.

When non-UTF-8 inputs are provided, any spans of invalid UTF-8 bytes will be passed through without any obfuscation.

Example:

$email      = '[email protected]';
$obscured   = antispambot( $email );
$obscured === 'noreply@example.com';
// Hex-encoding also obscures characters with percent-encoding.
$obscured   = antispambot( $email, 1 );
$obscured === '%6eore%70l%79@%65x%61mple%2e%63%6fm';
// Non-UTF-8 characters are not obfuscated. "\xFC" is Latin1 "ü".
$obscured   = antispambot( "b\[email protected]" );
$obscured === 'b�cher@library.de';
$obscured === "b\xFCcher@library.de"

No Hooks.

Returns

String. Converted email address.

Usage

antispambot( $email_address, $hex_encoding );
$email_address(string) (required)
Email address.
$hex_encoding(int)

Set to 1 to enable hex encoding.

0 - encodes only with integers ({).
1 - encodes to hex (&x7B;).
Default: 0

Examples

#1 Encode email

echo antispambot('[email protected]');

// In the code: mymail@gmail.com

// On the screen: [email protected]

Changelog

Since 0.71 Introduced.
Since 7.1.0 Masquerades multibyte characters.

antispambot() code WP 7.1

function antispambot( $email_address, $hex_encoding = 0 ) {
	$obfuscated     = '';
	$at             = 0;
	$end            = strlen( $email_address );
	$invalid_length = 0;

	while ( $at < $end ) {
		$was_at = $at;
		if (
			0 === _wp_scan_utf8( $email_address, $at, $invalid_length, null, 1 ) &&
			0 === $invalid_length
		) {
			break;
		}

		$character_length = $at - $was_at;

		if ( $character_length > 0 ) {
			$character = substr( $email_address, $was_at, $character_length );

			switch ( rand( 0, 1 + $hex_encoding ) ) {
				case 0:
					$code_point  = mb_ord( $character );
					$obfuscated .= "&#{$code_point};";
					break;

				case 1:
					$obfuscated .= $character;
					break;

				case 2:
					for ( $i = 0; $i < $character_length; $i++ ) {
						$hex_value   = bin2hex( $character[ $i ] );
						$obfuscated .= "%{$hex_value}";
					}
					break;
			}
		}

		if ( 0 !== $invalid_length ) {
			$obfuscated .= substr( $email_address, $at, $invalid_length );
		}

		$at += $invalid_length;
	}

	return str_replace( '@', '&#64;', $obfuscated );
}