tags:

views:

75

answers:

3

I am working on a Symfony project and I currently have this:

<?php echo preg_replace('/\n/','<br />', $review->getComments()); ?>

and would very much like to be able to make all getters add html line breaks so i don't have to pepper my code with preg_replace. the $object->getFieldname methods are work automatically so I am looking to extend this somewhere to globally add a new method. What is the best approach here?

+1  A: 

How about:

str_replace("\n",'<br />', $review->getComments());
Charlie Brown
+1  A: 

I think the best idea would be to add a getCommentsHtml() method onto your review object, which does something like:

return preg_replace('/\n/','<br />', $this->getComments());

Then you can use $review->getCommentsHtml() to format them using HTML. Also as Charlie mentioned, maybe str_replace would be better to use, as using a regular expression to change \n's into <br />'s may be a little bit of overkill :)

So if you don't want to have your code littered with replaces like this, I think putting a helper method on the classes that you'd like to format nicely would be the best way to go :)

nevelis
This is close to what I am wanting, I apologize for not making my questions a bit clear I have updated it.
Ben
+4  A: 

Seems like everyone forgot about nl2br() which is a function that does exactly that in PHP.

nl2br($review->getComments());

EDIT: At the time of this writing, everyone else uses preg_replace().

Andrew Moore
nl2br > str_replace : more readability =)
Clement Herreman