对于我的Zend Framework库,我有这个缩进代码的视图助手。
我在下面的代码中添加了解决方案
<?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);
我想做的是从带有textarea标签的行中删除X空白字符。其中X匹配代码缩进的空格数,在上面的示例中,它是6个空格。
答案 0 :(得分:0)
$html = preg_replace('~<textarea(.*?)>\s*(.*?)\s*</textarea>~si',
'<textarea$1>$2</textarea>', $html);
试试这个正则表达式。应修剪textarea
内容的内容。 这是你需要的吗?
或强>:
$html = preg_replace_callback('~<textarea(.*?)>(.*?)</textarea>~si', function($matches){
$matches[2] = trim($matches[2]); // trim 2nd capture (inner textarea)
return "<textarea{$matches[1]}>{$matches[2]}</textarea>";
}, $html);