views:

98

answers:

4

I am trying to improve my in-site personal messaging system by making it look nicer and feel more like e-mail. I currently add > before each line of replied text, but I would also like to add formatting such as font color to lines that start with ">" without the quotes. I am not sure how I would close the lines out with a regular expression. To open it I assume I should do something like the following?

$new_text = preg_replace("\> \is", "<font color=\"grey\">> ", $text);
A: 
preg_replace("/^(>.*)$/im", "<span style=\"color: red;\">\\1</span>", $reply);
Sean Bright
This works, but had one small error, fixed below:preg_replace("/^(>.*)$/im", "<span style=\"color: red;\n\">\\1</span>", $reply);
James Simpson
Fixed. Glad it worked.
Sean Bright
+1 for understanding what the user wanted.
Lance Roberts
That regexp looks wrong, it would match the whole variable as long as it started with a ">"....Might as well use echo "<span style=\"color: red;\">".$reply."</span>"
Question Mark
@Dougle - It matches each line in a multiline $reply that starts with a > and replaces it with the match, wrapped in a span. It does work correctly, as the OP mentioned. Give it a try to prove it to yourself.
Sean Bright
@Dougle - I see why you are confused now. The `/im` at the end of the expression is the key. The `m` changes the meaning of `^` and `$`. See http://us.php.net/manual/en/reference.pcre.pattern.modifiers.php for details.
Sean Bright
Ah my bad, apologies i didn't see the m flag
Question Mark
A: 
ereg_replace('^>(.*)', '<span class="quoted">&gt;\\1</span>', $content);
You
A: 
preg_replace('/(\n>[^\n]*)+/','<span class="reply">$1</span>', $message);

Something like that will enclose the quoted reply with something you can style up.

Question Mark
A: 

In addition to the good answers already posted, you may want to escape the captured text before treating it as HTML. With simple replacement, some characters in the quoted text (specifically '<', '>' and '&') will make your generated HTML invalid. (I'm assuming it isn't already escaped, or you would need to match ">" instead of ">".)

To ensure that the replacement yields valid HTML, you can do something like this:

function quote_markup($matches) {
    $quote = htmlspecialchars($matches[1]);
    return "<span style=\"color: red;\">$quote</span>",
}

preg_replace_callback("/^(>.*)$/im", 'quote_markup', $reply);
Tim Sylvester