开发者

Convert special characters like ' \t ' to " \t " (a real tab)

I want to make a CSV file importer on my website. I want the user to choose the delimiter.

The problem is when the form submits, the delimiter field is stored as '\t', for example, so when I'm parsing the file, I search for the string '\t' instead of a real TAB. It does the same thing with every special characters like \r, \n, etc...

I want to know the way or the function to use to convert these characters to their true repr开发者_Go百科esentation without using an array like:

  • 't' => "\t"
  • 'r' => "\r"
  • ...


You should probably decide what special chars will you allow and create a function like this one:

function translate_quoted($string) {
  $search  = array("\\t", "\\n", "\\r");
  $replace = array( "\t",  "\n",  "\r");
  return str_replace($search, $replace, $string);
}


echo str_replace("\\t", "\t", $string);

View an example here: http://ideone.com/IVFZk


PHP interpreter automatically escapes double quoted strings found in PHP source files, so echo "\t" actually indicates a TAB character.

On the contrary, when you read a string from any external source, the backslash assumes its literal value: a backslash and a 't'. You would express it in a PHP source as "\\t" (double quotes) or '\t' (single quotes), which is not what you want.

Sebastián's solution works, but PHP provides a native function for that.

stripcslashes() recognises C-like sequences (\a, \b, \f, \n, \r, \t and \v), as well as octal and hexadecimal representation, converting them to their actual meaning.

// C-like escape sequence
stripcslashes('\t') === "\t"; // true;

// Hexadecimal escape sequence
stripcslashes('\x09') === "\t"; // true;

// Octal escape sequence
stripcslashes('\011') === "\t"; // true;


Doesnt look like SO is leaving the tab in quotes, but tabbing once in any pad then copying into quotes should work.

$data = str_replace("\t", " ", $data);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜