将新行从 PHP 替换为 JavaScript
Replace new lines from PHP to JavaScript
情况很简单:
我发布了一个带有文本区域的纯HTML表单。然后,在PHP中,我根据表单的内容注册一个JavaScript函数。
这是使用以下代码完成的:
$js = sprintf("window.parent.doSomething('%s');", $this->textarea->getValue());
就像一个魅力,直到我尝试处理换行符。我需要用字符 13 替换换行符(我相信),但我无法找到有效的解决方案。我尝试了以下方法:
$textarea = str_replace("'n", chr(13), $this->textarea->getValue());
以及以下内容:
$js = sprintf("window.parent.doSomething('%s');", "'+String.fromCharCode(13)+'", $this->textarea->getValue());
有没有人知道我如何正确处理这些换行符?
你快到了,你只是忘了实际替换换行符。
这应该可以解决问题:
$js = sprintf("window.parent.doSomething('%s');"
, preg_replace(
'#'r?'n#'
, '" + String.fromCharCode(13) + "'
, $this->textarea->getValue()
);
你的意思是:
str_replace("'n", ''n', $this->textarea->getValue());
将所有换行符替换为文本字符串 ''n'
。
但是,您最好将其编码为 JSON:
$js = sprintf(
"window.parent.doSomething('%s');",
json_encode($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...
使用
str_replace(array("'n'r", "'n", "'r"), char(13), $this->textarea->getValue());
这应该用 char(13) 替换字符串中的所有新行
相关文章:
- javascript替换换行符和特殊字符
- 用JavaScript替换Android WebView模板上的html文本
- 使用javascript替换网页上的文本
- Javascript替换字节数组序列
- 使用Jquery/Javascript替换CSS属性
- 使用javascript替换后面跟着@的文本
- Javascript:替换冒号和逗号字符
- 如何使用Javascript替换和隐藏Div内容
- 使用javascript替换字符串中除第一个和最后一个之外的所有字符
- 如何用javascript替换Jquery字符串上的新参数
- 使用JavaScript替换类名值
- javascript替换单个字符串
- 可以't删除“;C: fakepath "使用javascript替换和regex
- 如何用JavaScript替换HTML字符串
- 我需要javascript替换regex方面的帮助
- JavaScript:替换字符串两边的字符
- 用JQuery/Javascript替换字符串中的所有逗号
- 用Javascript替换图像和图像标题/alt文本
- 如何在 javascript 替换新图像/标题后正确显示 css 工具提示
- 使用 JavaScript 替换 VisualForce 页面上的文本