duanheye7909 2013-07-07 20:14
浏览 41
已采纳

删除html内容中textarea标记内的前面的空格

For my Zend Framework library i have this view-helper that indents code.

I have added the solution in the code below

<?php

class My_View_Helper_Indent
{

    function indent($indent, $string, $space = ' ')
    {
        if($string == '') {
            return '';
        }
        $indent = str_repeat($space, $indent);
        $content = $indent . str_replace("
", "
" . $indent, rtrim($string)) . PHP_EOL;           

// BEGIN SOLUTION TO PROBLEM
// Based on user CodeAngry's answer
$callback = function($matches) use ($indent) {
    $matches[2] = str_replace("
" . $indent, "
", $matches[2]);
    return '<textarea' . $matches[1] . '>' . $matches[2] . '</textarea>';
};
$content = preg_replace_callback('~<textarea(.*?)>(.*?)</textarea>~si', $callback, $content);       
// END 

        return $content;
    }
}

And with the following test code..

$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);

What i would like to do, is to remove X whitespace characters from lines with the textarea tags. Where X matches the number of spaces that the code was indented, in the example above it's 6 spaces.

  • 写回答

1条回答 默认 最新

  • duancan1900 2013-07-07 20:18
    关注
    $html = preg_replace('~<textarea(.*?)>\s*(.*?)\s*</textarea>~si',
        '<textarea$1>$2</textarea>', $html);
    

    Try this regular expression. Should trim the contents of your textarea contents. Is this what you need?

    OR:

    $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);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化