Tomasz Decker
Tomasz Decker

Reputation: 124

Can't remove whitespaces from textarea

I have two files. First file is a form and the second file displays result.

First file:

<form action="show.php" method=post>
<textarea name="test" cols=40 rows=6>
</textarea>
<input type=submit value="submit">
</form>

Second file:

<?php
$text = trim($_POST['test']);
$textAr = explode("\n", $text);

for ($i=0; $i<sizeof($textAr); $i++)
{
    $link = str_replace(" ", "", $textAr[$i]);
    echo $link."---<br>";
}
?>

When I enter in the form for example

one
two
three

the result is:

one ---
two ---
three---

at the end on the strings: one and two there are whitespaces that I can't remove. Can anybody help me with this?

Thanks I used $link = str_replace("\r", "", $textAr[$i]) and now everything is ok

Upvotes: 0

Views: 4221

Answers (6)

Er Jagdish Patel
Er Jagdish Patel

Reputation: 193

I know its late but may help others.

use this in when document indentation is required.

$(document).ready(function()
{
    $('textarea').each(function(){
            $(this).val($(this).val().trim());
        }
    );
});

Upvotes: 1

Gras Double
Gras Double

Reputation: 16373

Basically, textarea's linebreaks are \r\n in Internet Explorer, and \n in all other browsers (including Mac's). IE uses \n too since version 9.


There are numerous ways to fix your code. For example, you could try preg_split() :

preg_split('/(?:\r\n|\n)/', $text);

However, I haven't tested the performances of this proposal.

Also, very important, be sure to put the \r\n before the \n in the regex!


Besides, trim() is way more suited than str_replace() (of course if you still need it).

Upvotes: 1

Matt K
Matt K

Reputation: 6708

Try nl2br() function, could be carriage return or new line (\r\n, \n\r, \n and \r).

Upvotes: 0

bardiir
bardiir

Reputation: 14782

Maybe it's non space whitespaces like non-break-spaces (nbsp) or some part of a linebreak combination?

Upvotes: 0

osoner
osoner

Reputation: 2415

You can use trim function instead of using str_replace to do that.

Upvotes: 1

Matt H
Matt H

Reputation: 6532

Use trim() instead of str_replace

Upvotes: 1

Related Questions