对于我的库,我有一个视图-帮助程序,它可以缩进代码。
我在下面的代码中添加了解决方案
<?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个空格。
发布于 2013-07-07 20:18:55
$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);https://stackoverflow.com/questions/17515952
复制相似问题