2013-07-07 109 views
0

對於我的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個空格。

+0

在要刪除'' – Phliplip

+0

我通過設置替換部分爲' $ 2'來修正你的正則表達式。但是它並沒有給我想要的結果。 – Phliplip

+0

@Phliplip修復它,抱歉:)現在嘗試。 – CodeAngry