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
How to delete white spaces of a text in twig?
提问by KubiRoazhon
回答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':''}