将PHP中的新行替换为JavaScript
情况很简单: 我发布了一个带有文本区域的普通HTML表单。然后,在PHP中,我根据表单的内容注册一个JavaScript函数 这是使用以下代码完成的:将PHP中的新行替换为JavaScript,php,javascript,textbox,compatibility,Php,Javascript,Textbox,Compatibility,情况很简单: 我发布了一个带有文本区域的普通HTML表单。然后,在PHP中,我根据表单的内容注册一个JavaScript函数 这是使用以下代码完成的: $js = sprintf("window.parent.doSomething('%s');", $this->textarea->getValue()); 在我尝试处理新行之前,它就像一个符咒。我需要用char13替换换行符(我相信),但我无法找到一个有效的解决方案。我尝试了以下方法: $textarea = str_repla
$js = sprintf("window.parent.doSomething('%s');", $this->textarea->getValue());
在我尝试处理新行之前,它就像一个符咒。我需要用char13替换换行符(我相信),但我无法找到一个有效的解决方案。我尝试了以下方法:
$textarea = str_replace("\n", chr(13), $this->textarea->getValue());
$js = sprintf("window.parent.doSomething('%s');", "'+String.fromCharCode(13)+'", $this->textarea->getValue());
以及以下各项:
$textarea = str_replace("\n", chr(13), $this->textarea->getValue());
$js = sprintf("window.parent.doSomething('%s');", "'+String.fromCharCode(13)+'", $this->textarea->getValue());
有人知道我如何正确处理这些换行符吗?使用
str_replace(array("\n\r", "\n", "\r"), char(13), $this->textarea->getValue());
这应该将字符串中的所有新行替换为char(13)您要做的是:
str_replace("\n", '\n', $this->textarea->getValue());
将所有新行字符替换为文字字符串'\n'
但是,最好将其编码为JSON:
$js = sprintf(
"window.parent.doSomething('%s');",
json_encode($this->textarea->getValue())
);
这也将修复引号。你几乎就到了,只是忘记了实际替换换行符 这应该可以做到:
$js = sprintf("window.parent.doSomething('%s');"
, preg_replace(
'#\r?\n#'
, '" + String.fromCharCode(13) + "'
, $this->textarea->getValue()
);
您的问题已经在我们的代码库中的其他地方解决了 取自我们的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…这是正确的方法。但是您可以添加一些其他字符来完成检查文本字段为什么要替换\n
?你能指定你的目标吗?如果$This->textarea->getValue(),这也会失败
包含一个”
。javascript字符串中的换行符将导致错误。@nebulousGirl:OP希望转义一个字符串,以便它可以作为javascript字符串文本进行回显。Javascript字符串文字不能包含新行-它们需要转义序列“\n”
。