對於我的Zend Framework庫,我有這個縮進代碼的view-helper。在html內容的textarea標籤中刪除前面的空格
我已經加入下面
<?php
class My_View_Helper_Indent
{
function indent($indent, $string, $space = ' ')
{
if($string == '') {
return '';
}
$indent = str_repeat($space, $indent);
$content = $indent . str_replace("\n", "\n" . $indent, rtrim($string)) . PHP_EOL;
// BEGIN SOLUTION TO PROBLEM
// Based on user CodeAngry's answer
$callback = function($matches) use ($indent) {
$matches[2] = str_replace("\n" . $indent, "\n", $matches[2]);
return '<textarea' . $matches[1] . '>' . $matches[2] . '</textarea>';
};
$content = preg_replace_callback('~<textarea(.*?)>(.*?)</textarea>~si', $callback, $content);
// END
return $content;
}
}
並用以下的測試代碼中的代碼解決方案..
$content = 'This is some text' . PHP_EOL;
$content .= '<div>' . PHP_EOL;
$content .= ' Text inside div, indented' . PHP_EOL;
$content .= '</div>' . PHP_EOL;
$content .= '<form>' . PHP_EOL;
$content .= ' <ul>' . PHP_EOL;
$content .= ' <li>' . PHP_EOL;
$content .= ' <label>inputfield</label>' . PHP_EOL;
$content .= ' <input type="text" />' . PHP_EOL;
$content .= ' </li>' . PHP_EOL;
$content .= ' <li>' . PHP_EOL;
$content .= ' <textarea cols="80" rows="10">' . PHP_EOL;
$content .= 'content of text area' . PHP_EOL;
$content .= ' this line is intentionally indented with 3 whitespaces' . PHP_EOL;
$content .= 'content of text area' . PHP_EOL;
$content .= ' </textarea>' . PHP_EOL;
$content .= ' </li>' . PHP_EOL;
$content .= ' </ul>' . PHP_EOL;
$content .= '</form>' . PHP_EOL;
$content .= 'The end';
echo $this->view->indent (6, $content);
什麼,我想這樣做,是除去X空格字符從具有textarea標籤的行開始。其中X與代碼縮進的空格數相匹配,在上面的示例中,它是6個空格。
在要刪除'
不,只有通過我的縮進函數添加的空格。假設用戶在提交表單前有意在textarea中縮進一行,並且由於錯誤而重新顯示錶單,那麼我不希望那些有意添加的空格消失。 – Phliplip