一个用于对输入字符串进行 QP 编码的函数(为 PHP < 5.3 编写的),并且
同时进行换行,以避免根据 SpamAssassin 的 MIME QP LONG LINE 规则进行分类。感谢 Matt Jeffers 指出以下 quoted_printable 脚本中的错误!
<?php
function quoted_printable_encode($input, $line_max = 75) {
$hex = array('0','1','2','3','4','5','6','7',
'8','9','A','B','C','D','E','F');
$lines = preg_split("/(?:\r\n|\r|\n)/", $input);
$linebreak = "=0D=0A=\r\n";
$line_max = $line_max - strlen($linebreak);
$escape = "=";
$output = "";
$cur_conv_line = "";
$length = 0;
$whitespace_pos = 0;
$addtl_chars = 0;
for ($j=0; $j<count($lines); $j++) {
$line = $lines[$j];
$linlen = strlen($line);
for ($i = 0; $i < $linlen; $i++) {
$c = substr($line, $i, 1);
$dec = ord($c);
$length++;
if ($dec == 32) {
if (($i == ($linlen - 1))) {
$c = "=20";
$length += 2;
}
$addtl_chars = 0;
$whitespace_pos = $i;
} elseif ( ($dec == 61) || ($dec < 32 ) || ($dec > 126) ) {
$h2 = floor($dec/16); $h1 = floor($dec%16);
$c = $escape . $hex["$h2"] . $hex["$h1"];
$length += 2;
$addtl_chars += 2;
}
if ($length >= $line_max) {
$cur_conv_line .= $c;
$whitesp_diff = $i - $whitespace_pos + $addtl_chars;
if (($i + $addtl_chars) > $whitesp_diff) {
$output .= substr($cur_conv_line, 0, (strlen($cur_conv_line) -
$whitesp_diff)) . $linebreak;
$i = $i - $whitesp_diff + $addtl_chars;
} else {
$output .= $cur_conv_line . $linebreak;
}
$cur_conv_line = "";
$length = 0;
$whitespace_pos = 0;
} else {
$cur_conv_line .= $c;
}
} $length = 0;
$whitespace_pos = 0;
$output .= $cur_conv_line;
$cur_conv_line = "";
if ($j<=count($lines)-1) {
$output .= $linebreak;
}
} return trim($output);
} ?>