Welcome Guest, Not a member yet? Register   Sign In
Issue with \r\n and \t
#1

[eluser]EEssam[/eluser]
Hi guys,

Can the following be written more nicely:

.....

if ($this->input->post('newline') == '\r\n')
{
$newline = "\r\n";
}
elseif ($this->input->post('newline') == '\t')
{
$newline = "\t";
}
else
{
$newline = $this->input->post('newline');
}

.....
echo $this->dbutil->csv_from_result($query, $delimiter, $newline);

Thanks.
#2

[eluser]parrots[/eluser]
You could skip the else clause and just assign the value to the variable by default.

Code:
$newline = $this->input->post(’newline’);
if ($newline == ‘\r\n’) {
    $newline = “\r\n”;
} else if ($newline == ‘\t’) {
    $newline = “\t”;
}
#3

[eluser]EEssam[/eluser]
Hi parrots,

The problem with the code it's not flexible at all. What if the user entered:

\r\n\r\n

or:

\t\t

How can this be solved.

Thanks.
#4

[eluser]dbashyal[/eluser]
Code:
$newline = preg_replace('/\r\n/', "\r\n", $newline);
or,
$newline = preg_replace('/(\r|\n)/', "\r\n", $newline);

$newline = preg_replace('/\t/', "\t", $newline);

replaces every repeat.
#5

[eluser]parrots[/eluser]
\r\n\r\n would behave the same as it did in your original code -- it would be assigned to the newline variable. I think the problem you're seeing is that both of our if checks don't take account for cases like that. I'd suggest using regular expressions to do a replace on the string, it would be a lot more flexible...

Code:
$newline = $this->input->post(’newline’);
$newline = preg_replace('/\t/', "\t", $newline);

The second line replaces all instances of '\t' with a tab character. You could do the same for \r, \n, etc. Removed the if block completely.
#6

[eluser]EEssam[/eluser]
Thank you very much, my code looks much better now.




Theme © iAndrew 2016 - Forum software by © MyBB