![](/img/trans.png)
[英]Is there a way to tell if an end user will be able to handle <a href=“mailto:###”> links?
[英]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
$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('&','%26',rawurlencode(htmlspecialchars_decode(the_title()))); ?>">Apply</a>
使用 PHP 組合: str_replace('&','%26',rawurlencode(htmlspecialchars_decode(the_title())));
問題是 & 字符需要在 URL 中轉義,因為 & 被視為控制字符。
您可以使用 HTML 編碼對其進行轉義。 例如, &
是一個&
字符,  
是一個不間斷的空格。
在 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.