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 (@).
<script type="text/javascript">
document.getElementById('cloak3fd71e407852d6d7593b726a0f41ca38').innerHTML = '';
var prefix = 'ma' + 'il' + 'to';
var path = 'hr' + 'ef' + '=';
var addy3fd71e407852d6d7593b726a0f41ca38 = 'some@email.com' + '@';
addy3fd71e407852d6d7593b726a0f41ca38 = addy3fd71e407852d6d7593b726a0f41ca38 + '';
var addy_text3fd71e407852d6d7593b726a0f41ca38 = 'some@email.com' + '@' + '';document.getElementById('cloak3fd71e407852d6d7593b726a0f41ca38').innerHTML += '<a ' + path + '\'' + prefix + ':' + addy3fd71e407852d6d7593b726a0f41ca38 + '\'>'+addy_text3fd71e407852d6d7593b726a0f41ca38+'<\/a>';
</script>
The correct line in the script is shown below:
var addy1ef8a36d65e0cc59448f875761cc1465 = 'some' + '@';addy1ef8a36d65e0cc59448f875761cc1465 = addy1ef8a36d65e0cc59448f875761cc1465 + 'email' + '.' + 'com';
Any ideas why the strings are handled differently? Thanks in advance!
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
);
a-zA-Z0-9_
is more simply condensed to \w
.
doesn't need to be escaped in a character class.-
doesn't need to be escaped if it is at the start or end of the character class or if it immediately follows a "range of characters" in the character class (e.g. 0-9-
).+
after \S
may be a bad idea in some scenarios