Search code examples
phpjavascripttextboxcompatibility

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?


Solution

  • 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()
    );