繁体   English   中英

在 mailto href 链接中允许“&”字符

[英]Allow '&' Character in mailto href links

我有一个电子邮件mailto href 链接,当我在主题中使用&字符时,这会阻止在电子邮件主题行中此符号之后呈现任何代码。 Oil & Gas ,仅显示为Oil

在正常情况下,我只会将&更改为单词and ,但主题行是通过 Wordpress 中的帖子标题动态生成的。

有谁知道如何防止主题行中断,或者换句话说如何让&显示为文本字符?

代码的精简版本如下:

<a href="mailto:joe@example.com?subject=Oil&Gas">Apply</a>

尽管在网站的 HTML 中,这是被拉入使用的:

<a href="mailto:<?php echo $author_email;?>?subject=<?php the_title(); ?>">Apply</a>

任何帮助或想法都会很棒,我不确定这是否是 html、php 或 Javascript 解决方案?

您可以使用urlencode函数对字符串进行转义,以便安全使用,如下所示:

<a href="mailto:<?php echo $author_email;?>?subject=<?php echo urlencode(the_title()); ?>">Apply</a>

urlencode PHP 文档

您需要对标题进行urlencode()

<?php
$title = "Gas&Oil";
?>
<a href="mailto:a@mail.com?subject=<?= urlencode($title); ?>">Apply</a>

演示

此外,由于the_title()默认回显标题,因此您需要使用get_the_title() ,否则urlencode()将无效。 你可以在这里看到这个模拟:

<?php
function the_title() {
    echo "Gas & Oil";
}
function get_the_title() {
    return "Gas & Oil";
}
?>
<a href="mailto:a@mail.com?subject=<?=urlencode(the_title()); ?>">Apply</a><br> <!-- doesn't work -->
<a href="mailto:a@mail.com?subject=<?=urlencode(get_the_title()); ?>">Apply</a> <!-- works -->

演示

但是,这将对整个标题进行编码,从而更改您不一定需要编码的其他字符。 因此,为避免这种情况,仅将&替换为%26

<a href="mailto:a@mail.com?subject=<?=str_replace("&", "%26", the_title()); ?>">Apply</a><br> <!-- doesn't work -->
<a href="mailto:a@mail.com?subject=<?=str_replace("&", "%26", get_the_title()); ?>">Apply</a> <!-- works -->

尝试用“%26”或“&”替换符号:

<a href="mailto:<?php echo $author_email;?>?subject=<?php str_replace('&', '%26', the_title()); ?>">Apply</a>
<a href="mailto:<?php echo $author_email;?>?subject=<?php echo str_replace('&amp;','%26',rawurlencode(htmlspecialchars_decode(the_title()))); ?>">Apply</a>

使用 PHP 组合: str_replace('&amp;','%26',rawurlencode(htmlspecialchars_decode(the_title())));

问题是 & 字符需要在 URL 中转义,因为 & 被视为控制字符。

您可以使用 HTML 编码对其进行转义。 例如, &amp; 是一个&字符, &nbsp是一个不间断的空格。

在 JavaScript 中,您可以对主题和正文使用“encodeURIComponent”。 然后它将显示电子邮件中的所有特殊字符。

例子:

    const emailRequest = {
            to: "abc@xyz.com",
            cc: "abc@xyz.com",
            subject: "Email Request - for <CompanyName>",
            body: `Hi All, \r\n \r\n This is my company <CompanyName> 
            \r\n Thanks
        }

    const subject = encodeURIComponent(emailRequest.subject.replace("<CompanyName>",'ABC & ** Company'));
    const body = encodeURIComponent(emailRequest.body .replace("<CompanyName>", 'ABC & ** Company'));

    window.location.href = (`mailto:${emailRequest.to}?cc=${emailRequest.cc}&subject=${subject}&body=${body}`);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM