You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP如何将非ASCII字符转换为数值运算并避免输出乱码

问题根因
  • 代码逻辑冗余:先后读取word.txt和password.txt,两次读取结果都赋值给$words,第一次读取的内容被直接覆盖,属于无效代码。
  • 编码适配错误:用到的strlen()、ord()、chr()都是PHP原生单字节处理函数,仅支持ISO-8859-1编码的单字节字符。从你给出的示例字符和数值对应关系来看,你的测试文件是*CP1252(Windows-1252)*编码,虽然也是单字节编码,但直接输出时如果浏览器默认按UTF-8解析,就会显示为乱码。
  • 换行分割兼容性差:直接用chr(0x0A)分割换行,仅适配Linux系统的\n换行符,Windows系统的\r\n换行符会残留\r字符。
修正代码(适配CP1252编码文件,符合你的需求场景)
// 读取目标文件,去掉冗余的word.txt读取逻辑
$file = fopen("password.txt", "r") or die("File missing");
$wholefile = fread($file, filesize("password.txt"));
fclose($file);

// 用PHP_EOL兼容不同系统的换行符
$words = explode(PHP_EOL, $wholefile);

// 处理第一行内容
$str = $words[0];
for($i = 0; $i < strlen($str); $i++)
{
    $str[$i] = chr(ord($str[$i]) - 31);
}

// 转成UTF-8编码输出,适配所有浏览器的默认解析规则
echo mb_convert_encoding($str, "UTF-8", "Windows-1252");
通用多字节编码适配方案(如果你的文件是UTF-8等多字节编码可以用这个版本)

需要确保PHP开启了mbstring扩展(默认环境均已开启)

$file = fopen("password.txt", "r") or die("File missing");
$wholefile = fread($file, filesize("password.txt"));
fclose($file);
$words = explode(PHP_EOL, $wholefile);

$str = $words[0];
$newStr = '';
// 替换为你实际的文件编码,比如UTF-8、GBK等
$encoding = 'UTF-8';
for($i = 0; $i < mb_strlen($str, $encoding); $i++)
{
    $char = mb_substr($str, $i, 1, $encoding);
    $charCode = mb_ord($char, $encoding);
    $newStr .= mb_chr($charCode - 31, $encoding);
}

header("Content-Type: text/html; charset=UTF-8");
echo $newStr;
验证说明

你示例中的“字符在CP1252编码下的ord值为147,减31得到116,对应ASCII字符t,使用上述代码运行即可得到预期结果,不会出现乱码。

内容的提问来源于stack exchange,提问作者Csema。

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.21 12:57:04