Skip to main content

Converts email addresses characters to HTML entities to block spam bots.

<?php

    /**
     * Add leading zeros when necessary.
     *
     * If you set the threshold to '4' and the number is '10', then you will get
     * back '0010'. If you set the threshold to '4' and the number is '5000', then you
     * will get back '5000'.
     *
     * Uses sprintf to append the amount of zeros based on the $threshold parameter
     * and the size of the number. If the number is large enough, then no zeros will
     * be appended.
     *
     * Source: https://core.trac.wordpress.org/browser/tags/5.7.1/src/wp-includes/formatting.php?order=name#L2670
     *
     * @since 0.71
     *
     * @param int $number    number to append zeros to if not greater than threshold
     * @param int $threshold digit places number needs to be to not have zeros added
     *
     * @return string adds leading zeros to number if needed
     */
    function zeroise($number, $threshold)
    {
        return sprintf('%0'.$threshold.'s', $number);
    }

    /**
     * Converts email addresses characters to HTML entities to block spam bots.
     *
     * Source: https://core.trac.wordpress.org/browser/tags/5.7.1/src/wp-includes/formatting.php?order=name#L2806
     *
     * @since 0.71
     *
     * @param string $email_address email address
     * @param int    $hex_encoding  Optional. Set to 1 to enable hex encoding.
     *
     * @return string converted email address
     */
    function antispambot($email_address, $hex_encoding = 0)
    {
        $email_no_spam_address = '';

        for ($i = 0, $len = strlen($email_address); $i < $len; ++$i) {
            $j = rand(0, 1 + $hex_encoding);
            if (0 == $j) {
                $email_no_spam_address .= '&#'.ord($email_address[$i]).';';
            } elseif (1 == $j) {
                $email_no_spam_address .= $email_address[$i];
            } elseif (2 == $j) {
                $email_no_spam_address .= '%'.zeroise(dechex(ord($email_address[$i])), 2);
            }
        }

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

    // echo antispambot('user@example.com');