Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace new lines from PHP to JavaScript

Situation is simple:

I post a plain HTML form with a textarea. Then, in PHP, I register a JavaScript function depending on the form's content.

This is done using the following code:

$js = sprintf("window.parent.doSomething('%s');", $this->textarea->getValue());

Works like a charm, until I try to process newlines. I need to replace the newlines with char 13 (I believe), but I can't get to a working solution. I tried the following:

$textarea = str_replace("\n", chr(13), $this->textarea->getValue());

And the following:

$js = sprintf("window.parent.doSomething('%s');", "'+String.fromCharCode(13)+'", $this->textarea->getValue());

Does anyone have a clue as to how I can process these newlines correctly?

like image 867
Sherlock Avatar asked Jan 19 '26 01:01

Sherlock


1 Answers

You were almost there you just forgot to actually replace the line-breaks.

This should do the trick:

$js = sprintf("window.parent.doSomething('%s');"
    , preg_replace(
              '#\r?\n#'
            , '" +  String.fromCharCode(13) + "'
            , $this->textarea->getValue()
);
like image 81
Potherca Avatar answered Jan 20 '26 14:01

Potherca



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!