3

情况很简单:

我发布了一个带有文本区域的纯 HTML 表单。然后,在 PHP 中,我根据表单的内容注册了一个 JavaScript 函数。

这是使用以下代码完成的:

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

在我尝试处理换行符之前,它就像一个魅力。我需要用 char 13 替换换行符(我相信),但我无法找到可行的解决方案。我尝试了以下方法:

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

以及以下内容:

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

有没有人知道我如何正确处理这些换行符?

4

4 回答 4

3

您几乎就在那里,您只是忘记实际替换换行符。

这应该可以解决问题:

$js = sprintf("window.parent.doSomething('%s');"
    , preg_replace(
              '#\r?\n#'
            , '" +  String.fromCharCode(13) + "'
            , $this->textarea->getValue()
);
于 2012-06-14T10:36:11.610 回答
1

你的意思是:

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

用文字字符串替换所有换行符'\n'


但是,您最好将其编码为 JSON:

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

这也将修复报价。

于 2012-06-07T16:22:25.187 回答
1

您的问题已经在我们代码库的其他地方得到解决......

取自我们的 WebApplication.php 文件:

    /**
     * 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);
        }
    }

您感兴趣的是:

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

请注意,在您的问题中sprintf,您忘记了 str_replace...

于 2012-06-14T10:37:28.570 回答
-1

采用

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

这应该用 char(13) 替换字符串中的所有新行

于 2012-06-07T16:19:08.357 回答