我对 cakePHPs Sanitize::clean() 方法到底应该做什么有点困惑。目前,当我添加记录时,我正在这样做:
$this->request->data = Sanitize::clean($this->request->data, array('encode' => true, 'remove_html' => true));
但是,当他们使用 & 并在文本区域中按 enter 时,这仍然会在我的数据库中留下 & 和 \n。我怎样才能阻止这个?我认为 remove_html => true 会这样做吗?
我需要做一个 str_replace()
此外,其中一些带有 \n 的记录有数百个尾随反斜杠,这意味着它们显示的任何视图都会中断。
有人能指出我正确的方向吗?谢谢
根据修女的回答更新
我现在在清理之后添加了以下内容:
foreach ($this->request->data['Expense'] as &$expense) {
$expense['detail'] = Sanitize::stripWhitespace($expense['detail']);
}
unset($expense);
但是,它确实删除了空格,但仍然留下了很多\n\n\n\n\n\
下面是 $this->request->data 的调试:
array(
'submit' => 'Save',
'Expense' => array(
(int) 0 => array(
'date' => array(
'day' => '27',
'month' => '06',
'year' => '2013'
),
'sitename' => 'test',
'detail' => 'test test\n\ntest\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n',
'ExpenseCode' => array(
'ExpenseCode' => '1'
),
'billable' => '1',
'amount' => '1',
'miles' => '',
'total' => '1',
'billable_mileage' => '',
'recorded_global_mileage_rate' => '0.4'
),
(int) 1 => array(
'date' => array(
'day' => '27',
'month' => '06',
'year' => '2013'
),
'sitename' => 'test',
'detail' => '\n\n\n\n\n\n\n\n\n\n\n\n\n\ntest',
'ExpenseCode' => array(
'ExpenseCode' => '4'
),
'billable' => '1',
'amount' => '10',
'miles' => '',
'total' => '10',
'billable_mileage' => '',
'recorded_global_mileage_rate' => '0.4'
)
),
'CashFloat' => array(
'amount' => ''
),
'ExpenseClaim' => array(
'user_id' => '3',
'claim_status_id' => '1'
)
)
我真的想把 thouse \n 去掉,因为我不希望它们破坏视图。
更多结果
即使我删除了 cake 函数并通过以下方式直接内联使用它的代码:
$expense['detail'] = preg_replace('/\s{2,}/u', ' ', preg_replace('/[\n\r\t]+/', '', $expense['detail']));
我仍然从循环中得到相同的 (debug($expense['detail']) :
'test 10 spaces before this then pressing enter lots \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n'
我还尝试了一个根本不起作用的基本 trim()。
工作解决方案(除了 &)
这将删除任意数量的
\n
从字符串
foreach ($this->request->data['Expense'] as &$expense) {
$expense['detail'] = str_replace("\\n", ' ', $expense['detail']);
$expense['detail'] = Sanitize::stripWhitespace($expense['detail']);
}
// Unset referance var from above loop
unset($expense);
决定保留 &
并且html_entity_decode()
在视图中回显时使用
希望对某人有所帮助!