php 如何删除树枝中文本的空格?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38607327/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 01:39:43  来源:igfitidea点击:

How to delete white spaces of a text in twig?

phpsymfonytwig

提问by KubiRoazhon

I'm using the twig template engine while using symfony2. I'm trying to find a way to delete the white spaces from a text.

我在使用 symfony2 时使用了树枝模板引擎。我试图找到一种方法来删除文本中的空格。

For example, I playshall become Iplay.

例如,I play应变为Iplay

I've tried:

我试过了:

回答by dlondero

First let's see what you tried and why that wasn't working:

首先让我们看看您尝试了什么以及为什么它不起作用:

  • Spaceless: is not working because "Use the spaceless tag to remove whitespace betweenHTML tags, not whitespace withinHTML tags or whitespace in plain text" see spaceless documentation.
  • Trim: is not working because "The trim filter strips whitespace (or other characters) from the beginningand endof a string" see trim documentation.
  • Spaceless: 不起作用,因为“使用 spaceless 标签删除HTML 标签之间的空白而不是HTML 标签内的空白或纯文本中的空白”,请参阅spaceless 文档
  • 修剪:不起作用,因为“修剪过滤器会从字符串的开头结尾去除空格(或其他字符)”,请参阅修剪文档

What you need to use is the following:

您需要使用的是以下内容:

{{ 'Some Text With Spaces'|replace({' ': ''}) }}

This will output:

这将输出:

SomeTextWithSpaces

More details in the documentation.

文档中的更多详细信息。

回答by Jayesh Chitroda

Try this:

尝试这个:

{{ "I plays"|replace({' ':''}) }}

回答by TOZ

You can also create your own filter to do that

您还可以创建自己的过滤器来做到这一点

Example :

例子 :

class MyExtensions extends \Twig_Extension
{
    public function getFilters()
    {
        return array(
            new \Twig_SimpleFilter('removeWhiteSpace', array($this, 'removeWhiteSpace'), array('is_safe' => array('html'))),
        );
    }

    public function removeWhiteSpace($string)
    {

       return preg_replace('/\s+/', '', $string);
    }
}

Declare it as service :

将其声明为服务:

myextensions.twig_extension:
      class: YourProject\YourBundle\Twig\MyExtensions
      public: false
      tags:
          - { name: twig.extension }

And call it in yours twig template :

并在您的树枝模板中调用它:

{{ "Test remove white space"|removeWhiteSpace }}

回答by jbator

For me this was not working when string contains non-breaking whitespaces:

对我来说,当字符串包含不间断空格时,这不起作用:

stringWithNonBreakingWhitespace|replace({' ':''}

To replace non-braking whitespace you have to use escape sequence:

要替换非制动空格,您必须使用转义序列:

stringWithNonBreakingWhitespace|replace({'\xc2\xa0':''}