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 に答える