我正在做php项目使用php excel..我已经创建了php类阅读excel表。该类返回简单的json字符串。该json字符串我将用于显示数据表在网页。但这个json字符串不能包含任何json字符。因此用户不能在excel表格中输入一些json字符。否则在编码json字符串时会产生很多错误。
防止这个问题的最好方法是什么?有一些好的方法来阅读excel表格(使用库)?
引号后加斜杠(转义)
<?php
$str = "Is your name O'Reilly?";
// Outputs: Is your name O''Reilly?
echo addslashes($str);
?>
这是一个适合JSON的方法。
function json_string_encode($str) {
$callback = function($match) {
if ($match[0] === '''') {
return $match[0];
} else {
$printable = array('"' => '"', '''' => '''', "'b" => 'b', "'f" => 'f', "'n" => 'n', "'r" => 'r', "'t" => 't');
return isset($printable[$match[0]])
? ''''.$printable[$match[0]]
: '''u'.strtoupper(current(unpack('H*', mb_convert_encoding($match[0], 'UCS-2BE', 'UTF-8'))));
}
};
return '"' . preg_replace_callback('/''.|[^'x{20}-'x{21}'x{23}-'x{5B}'x{5D}-'x{10FFFF}/u', $callback, $str) . '"';
}