Twig: Can't figure out how to remove / replace ` `

Created on 30 Aug 2018  路  6Comments  路  Source: twigphp/Twig

I need to replace   with normal spaces so that |trim will work as expected. However, neither copying the   char into a |replace filter nor literally writing ' ' work. How can I do this?

Most helpful comment

First, get your whole HTML div and convert it to the string

convertHtmlToText(str)
{
   str = str.toString();
  return str.replace(/<[^>]*(>|$)|&nbsp;|&zwnj;|&raquo;|&laquo;|&gt;/g, ' ');
}

you will get the text without HTML tag and &nbsp etc

This is a solution for HTML tag and &nbsp etc and you can remove the useless conditions

All 6 comments

writing the HTML entity literally won't help you to replace the non-breaking space char, as they're not the same strings (HTML entities gets replaced by their corresponding char only when parsing HTML).

To replace chars, use a string containing a non-breaking space for the replacement. Copy-pasting may not work fine, as your software might turn it into a normal space at some point of the process (and it would probably hurt maintenance due to not being visible that it's not a normal space). Using an escape sequence is a safer solution. See https://twigfiddle.com/nn8ss5 for an example.

@stof Hey, fantastic, that works! I never knew about escape sequences before. That's super useful.

Well, it looks like supported escape sequences are not documented in the place describing string literals (except saying that backslashes need escaping): https://twig.symfony.com/doc/2.x/templates.html#literals

The escape sequences in Twig string literals are the one supported by https://secure.php.net/stripcslashes

First, get your whole HTML div and convert it to the string

convertHtmlToText(str)
{
   str = str.toString();
  return str.replace(/<[^>]*(>|$)|&nbsp;|&zwnj;|&raquo;|&laquo;|&gt;/g, ' ');
}

you will get the text without HTML tag and &nbsp etc

This is a solution for HTML tag and &nbsp etc and you can remove the useless conditions

First I hope you know the actual difference between this two characters. If you do and you still need the replacement you can do it with a custom filter:

public function clearNbsp($str)
{
    $entities = str_replace('&nbsp;', ' ', htmlentities($str));
    return html_entity_decode($entities);
}

{{ text|striptags|raw }}

Important is, that the striptags come before the |raw filter.

Was this page helpful?
0 / 5 - 0 ratings