简体   繁体   中英

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?

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

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.

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...

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM