phpjoomlapreg-replacecloaking

JHtml-"email.cloak" doesn't recognize email address when using preg_replace() in joomla


I try to substitute an email-address within a text in a module with php using JHtml::_("email.cloak", "some@email.com"), in order to cloak it on a joomla 3.9.2 webpage.

using following sample code:

<div>
<?php
    $text = "This is a text with some@email.com an e-mail address in it";
    $test_text_email = "some@email.com";
    echo JHtml::_("email.cloak", $test_text_email)."<br>";
    echo preg_replace('/([a-zA-Z0-9_\-\.]*@\\S+\\.\\w+)/', JHtml::_("email.cloak", "$1"),$text)."<br>";
?></div>

Jhtml:_("email.cloak",... works great when just handing over a simple string (see $test_text_email below). When searching for an email address within a text using preg_replace, the email substring is found correctly, yet the cloaking doesn't work correctly as the function doesn't seem to recognize the "@" symbol anymore with the following result:

<span id="cloak7c9ea7a5340755f2f7e1d4f0c8b45675"><a href="mailto:some@email.com">some@email.com</a></span>
This is a text and <span id="cloak88a24a939973cdd7ec9f3d1fb591b7a5"><a href="mailto:some@email.com@">some@email.com@</a></span> an e-mail address 

The generated javascript proves the correct substring found by preg_replace(), but without any cloaking happening, just an @ symbol is added at the end (&#64).

<script type="text/javascript">
            document.getElementById('cloak3fd71e407852d6d7593b726a0f41ca38').innerHTML = '';
            var prefix = '&#109;a' + 'i&#108;' + '&#116;o';
            var path = 'hr' + 'ef' + '=';
            var addy3fd71e407852d6d7593b726a0f41ca38 = 'some@email.com' + '&#64;';
            addy3fd71e407852d6d7593b726a0f41ca38 = addy3fd71e407852d6d7593b726a0f41ca38 + '';
            var addy_text3fd71e407852d6d7593b726a0f41ca38 = 'some@email.com' + '&#64;' + '';document.getElementById('cloak3fd71e407852d6d7593b726a0f41ca38').innerHTML += '<a ' + path + '\'' + prefix + ':' + addy3fd71e407852d6d7593b726a0f41ca38 + '\'>'+addy_text3fd71e407852d6d7593b726a0f41ca38+'<\/a>';
    </script>

The correct line in the script is shown below:

    var addy1ef8a36d65e0cc59448f875761cc1465 = 's&#111;m&#101;' + '&#64;';addy1ef8a36d65e0cc59448f875761cc1465 = addy1ef8a36d65e0cc59448f875761cc1465 + '&#101;m&#97;&#105;l' + '&#46;' + 'c&#111;m';

Any ideas why the strings are handled differently? Thanks in advance!


Solution

  • You can't perform manipulations on the replacement parameter of preg_replace(). You will need to call preg_replace_callback().

    Code: (Demo)

    $text = "This is a text with some@email.com an e-mail address in it";
    
    echo preg_replace_callback(
            '~[\w.-]+@(?:[\w-]+\.)+\w+~',
            function($m) {
                return JHtml::_("email.cloak", $m[0]);
            },
            $text
         );