Alex L.
Alex L.

Reputation: 821

preg_replace space to line break with twig

I would like to replace space in string to line break.

Before

1 2 3 4

After preg_replace :

1
2
3
4

This is my code:

$m_cart = preg_replace('/\s/', '\n', $session->get('cart'));
return $this->render('FooSiteBundle:Site:bar.html.twig', array('cart' => $m_cart));

and this is my view with twig:

{{ cart }}

the result:

\n1\n2\n3\n4

but I would like to have

1
2
3
4

Upvotes: 0

Views: 2707

Answers (3)

Joe Mewes
Joe Mewes

Reputation: 31

Would nl2br help?

http://twig.sensiolabs.org/doc/filters/nl2br.html

so try:

{{ cart|nl2br }}

Upvotes: 3

Peter Bailey
Peter Bailey

Reputation: 105914

The newline escape sequence \n isn't interpreted by single-quote-delimited strings (as a point, /[no]/ escape sequences are)

The simple answer is to just change '\n' to "\n".

I invite you to read more about PHP's string delimiters and how they differ

Upvotes: 4

Will
Will

Reputation: 1619

Change '\n' to "\n". That is, add double quotes. PHP parses them differently, and having double quotes enables you to use special characters like \n.

Upvotes: 1

Related Questions