Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Can't figure out how to remove / replace   #2742

Closed
su-narthur opened this issue Aug 30, 2018 · 6 comments
Closed

Can't figure out how to remove / replace   #2742

su-narthur opened this issue Aug 30, 2018 · 6 comments

Comments

@su-narthur
Copy link

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?

@stof
Copy link
Member

stof commented Aug 30, 2018

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.

@su-narthur
Copy link
Author

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

@stof
Copy link
Member

stof commented Aug 31, 2018

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

@iamsahilralkar
Copy link

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

@Adgivi
Copy link

Adgivi commented Jun 16, 2020

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);
}

@MichaelBrauner
Copy link

{{ text|striptags|raw }}

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

No branches or pull requests

5 participants