【问题标题】:How to split a unicode string by a specified delimiter in php?如何在 php 中通过指定的分隔符拆分 unicode 字符串?
【发布时间】:2017-05-14 16:03:40
【问题描述】:

对不起,如果这个问题听起来很菜鸟。我的问题是我有一个文本文件,需要将数据导入数据库。

阅读过程很好,当我print_r时,它是正确的。

然后我需要用制表符(\t)分隔符来分割它。然后所有的unicode字符都被破坏了。

这是我的尝试:

<!DOCTYPE html>
<html>
  <head>
    <meta charset=utf-8>
    <title>Test page for project XY</title>
  </head>
  <body>
     <h1>Test Page</h1>
     <pre>
     <?php
include 'ChromePhp.php';
ChromePhp::log('Start read file!');
ini_set("default_charset", 'utf-8');
$handle = fopen("input.txt", "r");
if ($handle) {
    while (($line = fgets($handle)) !== false) {
        // process the line read.
        print_r($line); // if print the $line here, it's fine
        $myArray = preg_split("/[\t]/", $line); //=> broken unicode, adding u not work
        $myArray = explode("\t", $line);//=> same
        print_r($myArray);
    }

    fclose($handle);
} else {
    // error opening the file.
    // ChromePhp::log('Cant open file!');
    print_r ('Cant open file!');
} 
?>


     </pre>
  </body>
</html>

更新:我尝试了这个作为建议,但仍然不起作用:(

mb_internal_encoding("UTF-8");
mb_regex_encoding("UTF-8"); 
$tab="\t";
$myArray=(mb_split($tab,$line));
print_r($myArray);`

【问题讨论】:

  • 你可能只需要 unicode 修饰符:preg_split("/[\t]/u", $line)
  • 嗨,我试过preg_split("/[\t]/u", $line),但是像��这样的字符仍然出现:(
  • 你的php源文件也是utf-8吗?
  • 是的。实际上,它是没有 BOM 的 UTF-8。我尝试切换到 UTF-8,但没有任何改变 :(

标签: php unicode split


【解决方案1】:

尝试在终端中运行它,我认为您的视图中有错误。尝试将标头指令放入 php 并说它 codepage = UTF-8。您还需要检查 php 文件代码页本身。

【讨论】:

  • 感谢您的关注。事实证明,input.txt 是用 UCS-2 编码的:p
猜你喜欢
  • 1970-01-01
  • 2010-11-29
  • 2013-03-03
  • 2018-05-05
  • 2011-03-29
  • 2010-11-10
  • 2014-03-02
  • 2011-07-22
  • 2013-10-30
相关资源
最近更新 更多