Sherlock
Sherlock

Reputation: 7597

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?

Upvotes: 3

Views: 261

Answers (4)

Kris
Kris

Reputation: 41837

Your problem has already been solved elsewhere in our codebase...

Taken from our WebApplication.php file:

    /**
     * Log a message to the javascript console
     *
     * @param $msg
     */
    public function logToConsole($msg)
    {
        if (defined('CONSOLE_LOGGING_ENABLED') && CONSOLE_LOGGING_ENABLED)
        {
            static $last = null;
            static $first = null;
            static $inGroup = false;
            static $count = 0;

            $decimals = 5;

            if ($first == null)
            {
                $first          = microtime(true);
                $timeSinceFirst = str_repeat(' ', $decimals) . ' 0';
            }

            $timeSinceFirst = !isset($timeSinceFirst)
                ? number_format(microtime(true) - $first, $decimals, '.', ' ')
                : $timeSinceFirst;

            $timeSinceLast = $last === null
                ? str_repeat(' ', $decimals) . ' 0'
                : number_format(microtime(true) - $last, $decimals, '.', ' ');

            $args = func_get_args();
            if (count($args) > 1)
            {
                $msg = call_user_func_array('sprintf', $args);
            }
            $this->registerStartupScript(
                sprintf("console.log('%s');", 
                    sprintf('[%s][%s] ', $timeSinceFirst, $timeSinceLast) .
                    str_replace("\n", "'+String.fromCharCode(13)+'", addslashes($msg))));

            $last = microtime(true);
        }
    }

The bit you are interested in is:

str_replace("\n", "'+String.fromCharCode(13)+'", addslashes($msg))

Note that in your questions' sprintf, you forgot the str_replace...

Upvotes: 1

Potherca
Potherca

Reputation: 14590

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

Upvotes: 3

Eric
Eric

Reputation: 97601

What you meant to do was:

str_replace("\n", '\n', $this->textarea->getValue());

Replace all new line characters with the literal string '\n'.


However, you'd do better to encode it as JSON:

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

That will fix quotes as well.

Upvotes: 1

paquettg
paquettg

Reputation: 1374

use

str_replace(array("\n\r", "\n", "\r"), char(13), $this->textarea->getValue());

This should replace all new lines in the string with char(13)

Upvotes: -1

Related Questions