我正在编写一个PHP脚本,将日式烹饪食谱从日语翻译成英语。这是宠物项目,不一定是完美的。我的策略是..。
我从命令行运行这个PHP脚本:
<?php
// Get contents of Japanese cooking website
$url = 'http://recipe.igamono.jp/?eid=1077379';
$context = stream_context_create(array('http' => array('header' => 'Accept-Charset: UTF-8, *;q=0')));
$html = file_get_contents($url, false, $context);
// Replace stuff
$html = preg_replace('/right/s', 'foobar', $html); // works
$html = preg_replace('/の/s', 'shazam!!', $html); // doesn't work
// Write output to a file
file_put_contents('output.html', $html);
?>我使用崇高文本编辑文件(translate.php),并确保使用: file / save with Encoding / UTF-8保存该文件
当我运行脚本时,除了替换の之外,一切都正常工作。の不发生替换。
然而,这个执行的工作:
<?php
$html = "one の two の";
$html = preg_replace('/の/s', 'shazam!!', $html);
file_put_contents('output.html', $html);
?>产出如下:
一个沙扎姆!!两个沙扎姆!!
有什么建议吗?我知道这是一个字符编码问题,但我似乎无法让它发挥作用。
更新:
下面是一个修改后的版本,它测试$html变量的UTF-8编码:
<?php
// Get contents of Japanese cooking website
$url = 'http://recipe.igamono.jp/?eid=1077379';
$context = stream_context_create(array('http' => array('header' => 'Accept-Charset: UTF-8, *;q=0')));
$html = file_get_contents($url, FILE_TEXT, $context);
if(mb_detect_encoding($html, 'UTF-8')) print("Yep, UTF-8 it is.\n");
if(! mb_detect_encoding($html, 'UTF-8', true)) print("Well, on second thought.. maybe not!\n");
?>产出如下:
是的,UTF-8是。 再想一想..。也许不会!
我的解决方案
以下是我想出的一个解决方案:
<?php
// Get contents of Japanese cooking website
$url = 'http://recipe.igamono.jp/?eid=1077379';
$html = file_get_contents($url);
// Convert HTML to UTF-8 from Japanese
$html = mb_convert_encoding($html, "UTF-8", "EUC-JP");
// Replace stuff
$html = preg_replace('/right/s', 'foobar', $html);
$html = preg_replace('/の/s', 'shazam!!', $html);
// Convert HTML back to Japanese character encoding
$html = mb_convert_encoding($html, "EUC-JP", "UTF-8");
// Write HTML to a file
file_put_contents('output.html', $html);
?>发布于 2016-02-14 01:10:04
建议:
$html = preg_replace('/[\x{306E}]/u', 'shazam!!', $html);更新:发现您要加载的页面不是UTF-8,而是EUC。做:
<?php
// Get contents of Japanese cooking website
$url = 'http://recipe.igamono.jp/?eid=1077379';
$context = stream_context_create(array('http' => array('header' => 'Accept-Charset: EUC-JP, *;q=0')));
$html = file_get_contents($url, false, $context);
// Replace stuff
$html = mb_convert_encoding($html, "UTF-8", "EUC-JP");
$html = preg_replace('/right/s', 'foobar', $html); // works
$html = preg_replace('/の/s', 'shazam!!', $html); // doesn't work
// Write output to a file
file_put_contents('output.html', $html);
?>我得到了“shazam!”

https://stackoverflow.com/questions/35387095
复制相似问题