Wrap email quotes with html element I'm wondering if I could handle the following situation with a single function or regex call. Given the folowing input:

Some text

&gt; Foo
&gt; Bar
&gt;&gt; Baz
&gt; Foo


The output should be:

Some text

&lt;blockquote&gt;
Foo
Bar
    &lt;blockquote&gt;
        Baz
    &lt;/blockquote&gt;
Foo
&lt;/blockquote&gt;


The following two functions do handle this situation, but I think there must be a more elegant way to handle it. I thought about regular expressions, but could not think of any pattern that replaces the input with the output (see above).



&lt;?php
function toArray($str, $currLevel = 0, $i = 0) {
  $return = array();
  $lines = explode("\n", $str);
  for($j = count($lines); $i &lt; $j; $i++) {
    $line = trim($lines[$i]);
    $level = preg_replace('/^((?:&gt;|\s)+).*/','\1', $line);
    $level = substr_count($level, '&gt;');
    if($level == $currLevel) {
      array_push($return, preg_replace('/^((?:&gt;|\s)+)(.*)/','\2', $line));
    }
    else if($level &gt; $currLevel) {
      array_push($return, toArray(join("\n", $lines), $currLevel  + 1, &amp;$i));
    } else if($level &lt; $currLevel) {
      $i--;
      return $return;
    }
  }

  return $return;
}

function toQuote($lines) {
  $return = "&lt;blockquote&gt;\n";
  foreach($lines as $line) {
    if(is_array($line)) {
      $return .= toQuote($line);
    }
    else {
      $return .= $line . "\n"; 
    }
  }
  $return .= "&lt;/blockquote&gt;\n";
  return $return;
}

$str = &lt;&lt;&lt;INPUT
  Some text

  &gt; Foo
  &gt; Bar
  &gt;&gt; Baz
  &gt; Foo
INPUT;

echo toQuotes(toArray($str));
This isn't much more elegant, but maybe you like it:

$text = "Some text

&gt; Foo
&gt; Bar
&gt;&gt; Baz
&gt; Foo
";

function clean($text) {
  $result = "";
  $lines = explode("\n", $text);
  foreach($lines as $key =&gt; $line) {
    $lines[$key] = preg_replace('/(&gt;)+ /', '', $line);
  }
  return join("\n", $lines);
}

function quotes($text, $level = 1) {
  $search = str_repeat("&gt;", $level);
  $fstpos = strpos($text, $search);
  $sndpos = strrpos($text, $search);
  $sndpos = strpos($text, "\n", $sndpos);
  $middle = substr($text, $fstpos, $sndpos + 1);
  if($fstpos === false or $sndpos === false)
    return clean($middle, $search);
  $fst = clean(substr($text, 0, $fstpos), $search);
  $snd = clean(substr($text, $sndpos), $search);
  return $fst . "&lt;blockquote&gt;\n" . quotes($middle, $level + 1)  . "&lt;/blockqoute&gt;" . $snd;
}

echo quotes($text);