【发布时间】:2017-07-06 10:59:37
【问题描述】:
我正在读取并解析一个 ANSI 格式的 CSV 文件。在我解析它之前,我想删除所有不在白名单中的字符
// remove any odd characters from string
$match_list = "\x{20}-\x{5f}\x{61}-\x{7e}"; // basic ascii chars excluding backtick
$match_list .= "\x{a1}-\x{ff}"; // extended latin 1 chars excluding control chars
$match_list .= "\x{20ac}\x{201c}\x{201d}"; // euro symbol & left/right double quotation mark (from Word)
$match_list .= "\x{2018}\x{2019}"; // left/right single quotation mark (from word)
$cleaned_line = preg_replace("/[^$match_list]/u", "*",$linein);
问题是当它到达包含 ó(acute o)字符的行时返回 NULL。根据我的文本编辑器,这是 xF3,所以应该被允许。
为什么会在 preg_replace 中抛出错误?
更新 - 它似乎与文件有关 - 如果我将问题行从 CSV 文件复制并粘贴到我的 PHP 文件中,它可以正常工作。
更新 2 - 使用 preg_last_error() 我能够确定错误是:
PREG_BAD_UTF8_ERROR Returned by preg_last_error() if the last error was caused by malformed UTF-8 data (only when running a regex in UTF-8 mode).
我的文本编辑器刚刚将文件报告为 ANSI,但使用 unix 文件命令我得到了这个:
% file PRICE_LIST_A.csv
PRICE_LIST_A.csv: Non-ISO extended-ASCII text, with CRLF line terminators
% file DOLLARS_PRICE_LIST.csv
DOLLARS_PRICE_LIST.csv: ISO-8859 text, with CRLF line terminators
% file PRICE_LIST_B.csv
PRICE_LIST_B.csv: Non-ISO extended-ASCII text, with CRLF line terminators
% file PRICE_LIST_TEST.csv
PRICE_LIST_TEST.csv: ASCII text, with CRLF line terminators
看来我已经从同一个会计应用程序中获得了具有各种编码的文件。我猜这些不是有效的 Unicode
【问题讨论】:
-
为什么要替换preg? str_replace 不再适用于静态替换了吗?
-
好像work。
-
str_replace 不匹配模式?
-
显示
var_dump($linein);的输出,否则代码工作正常。 -
@Wiktor Stribiżew 谢谢,但它为我返回 NULL。 Unix 上的 PHP 5.6
标签: php regex preg-replace