HiveBrain v1.2.0
Get Started
← Back to all entries
patternphpMinor

Wrap email quotes with html element

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
emailwithquoteselementwraphtml

Problem

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

Some text

> Foo
> Bar
>> Baz
> Foo


The output should be:

Some text

Foo
Bar
    
        Baz
    
Foo


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).

|\s)+).*/','\1', $line);
$level = substr_count($level, '>');
if($level == $currLevel) {
array_push($return, preg_replace('/^((?:>|\s)+)(.*)/','\2', $line));
}
else if($level > $currLevel) {
array_push($return, toArray(join("\n", $lines), $currLevel + 1, &$i));
} else if($level Foo
> Bar
>> Baz
> Foo
INPUT;

echo toQuotes(toArray($str));

Solution

This isn't much more elegant, but maybe you like it:

$text = "Some text

> Foo
> Bar
>> Baz
> Foo
";

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

function quotes($text, $level = 1) {
  $search = str_repeat(">", $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 . "\n" . quotes($middle, $level + 1)  . "" . $snd;
}

echo quotes($text);

Code Snippets

$text = "Some text

> Foo
> Bar
>> Baz
> Foo
";

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

function quotes($text, $level = 1) {
  $search = str_repeat(">", $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 . "<blockquote>\n" . quotes($middle, $level + 1)  . "</blockqoute>" . $snd;
}

echo quotes($text);

Context

StackExchange Code Review Q#2655, answer score: 2

Revisions (0)

No revisions yet.