How to color cards (hearts and diamonds) red in Drupal 7 comments? I run a Drupal 7 website with Forum, Blog, Comment core modules enabled and a custom module (generates a block with Flash game and blocks with player rating) written by me.

The website is dedicated to a Russian card game and users often mention card colors in their comments when discussing some card riddle or a game:



Most users are older folks, who don't understand anything like HTML tags, so I have only enabled plain text comments for them.

My quesion is: in the plain text Comments - how to recognize the strings like K♥ or 7♦ and color them red?

The PHP code would be something like:

preg_replace(/(1?[0789JQKA][♥♦])/, '&lt;font color="red"&gt;\1&lt;/font&gt;', $str);


(I can improve the regex later) - but where/how to apply it in Drupal 7?
If you need it to be configurable/re-usable then a custom filter is the way to go as Mołot said. The idea is that the raw data is always stored, and the filter is applied upon display. This is all well and good, but if you don't ever need the original text I find this method to be an unnecessary performance overhead (especially when you involve regexs, as most filters do).

The other way is to intercept the comment body before it's saved, and apply your filter then. For this you can use hook_comment_presave():

function MYMODULE_comment_presave($comment) {
  $comment-&gt;comment_body[$comment-&gt;language][0]['value'] = string_replacement_function($comment-&gt;comment_body[$comment-&gt;language][0]['value']);
}


I know this method is 'frowned upon' (heaven forbid we alter someone's input, even if we want to control what goes in the database!), and I can think of at least 2 people who will downvote this if/when they see it. 

I think the benefits/drawbacks of both methods are pretty clear, though, so I'd advise you make a decision based on your use-case. If the module you implement to do this isn't being released back into the wild, I see no benefit in taking the extra performance hit here. 

But if you think you'll ever want to use this method to filter text elsewhere on the site (e.g. in node bodies), a custom filter would make more sense.