Encode a mail-subject-string to a encoded-word according to RFC2047 with awareness of special characters and total-linelength of 75.
Example: "Subject Test?" -> "=?ISO-8859-1?Q?Subject_Test=E4?="
<?php
function getSubjectEncoded($_str,$_charset='ISO-8859-1'){
// 27.08.2015 david jufer
// Convert an 8bit string to a encoded-word string (according to RFC2047) www.ietf.org/rfc/rfc2047.txt
// encoded-word = "=?" charset "?" encoding "?" encoded-text "?="
// An 'encoded-word' may not be more than 75 characters long, including 'charset', 'encoding', 'encoded-text', and delimiters.
// The "Q" encoding is similar to the "Quoted-Printable" content-transfer-encoding defined in RFC 2045
$ret = '';
$str = imap_8bit($_str);
$len = 7+strlen($_charset);
// remove linebreaks from imap_8bit, string chunks are too long
$str = str_replace("=\r\n",'',$str);
// insert linebreaks at right position, be aware of special chars ("?" "=E4") do not split them
$s = 0;
$l = 75-$len;
while(strlen($str)>$s){
$ts = $s;
if(substr($str,($s+$l)-2,1)=='='){
$s += $l-2;
}else if(substr($str,($s+$l)-1,1)=='='){
$s += $l-1;
}else{
$s += $l;
}
$ret .= "\r\n".substr($str,$ts,$s-$ts);
}
// remove first linebreak, replace SPACES with "_"
$ret = str_replace(' ','_',trim($ret));
// put together encoded-word
$ret = '=?'.$_charset.'?Q?'.str_replace("\r\n","?=\r\n =?".$_charset."?Q?",$ret)."?=";
// rückgabe
return $ret;
}
?>