#1802 left/right trim

This commit is contained in:
Antony D'Andrea
2017-02-18 19:25:35 +00:00
committed by Fabien Potencier
parent 30085c5e78
commit 7d8e75504c
4 changed files with 56 additions and 2 deletions
+1
View File
@@ -1,6 +1,7 @@
* 1.32.0 (2017-XX-XX)
* added a PSR-11 compatible runtime loader
* added `side` argument to `trim` to allow left or right trimming only.
* 1.31.0 (2017-01-11)
+17 -1
View File
@@ -1,5 +1,8 @@
``trim``
========
.. versionadded:: 1.32
The ``side`` argument was added in Twig 1.32.
.. versionadded:: 1.6.2
The ``trim`` filter was added in Twig 1.6.2.
@@ -17,13 +20,26 @@ and end of a string:
{# outputs ' I like Twig' #}
{{ ' I like Twig. '|trim(side='left') }}
{# outputs 'I like Twig. ' #}
{{ ' I like Twig. '|trim(' ', 'right') }}
{# outputs ' I like Twig.' #}
.. note::
Internally, Twig uses the PHP `trim`_ function.
Internally, Twig uses the PHP `trim`_, `ltrim`_, and `rtrim`_ functions.
Arguments
---------
* ``character_mask``: The characters to strip
* ``side``: The default is to strip from the left and the right (`both`) sides, but `left`
and `right` will strip from either the left side or right side only
.. _`trim`: http://php.net/trim
.. _`ltrim`: http://php.net/ltrim
.. _`rtrim`: http://php.net/rtrim
+26 -1
View File
@@ -163,7 +163,7 @@ class Twig_Extension_Core extends Twig_Extension
new Twig_SimpleFilter('upper', 'strtoupper'),
new Twig_SimpleFilter('lower', 'strtolower'),
new Twig_SimpleFilter('striptags', 'strip_tags'),
new Twig_SimpleFilter('trim', 'trim'),
new Twig_SimpleFilter('trim', 'twig_trim_filter'),
new Twig_SimpleFilter('nl2br', 'nl2br', array('pre_escape' => 'html', 'is_safe' => array('html'))),
// array helpers
@@ -945,6 +945,31 @@ function twig_in_filter($value, $compare)
return false;
}
/**
* Returns a trimmed string.
*
* @return string
*
* @throws Twig_Error_Runtime When an invalid trimming side is used (not a string or not 'left', 'right' or 'both')
*/
function twig_trim_filter($string, $characterMask = null, $side = 'both')
{
if (null === $characterMask) {
$characterMask = " \t\n\r\0\x0B";
}
switch ($side) {
case 'both':
return trim($string, $characterMask);
case 'left':
return ltrim($string, $characterMask);
case 'right':
return rtrim($string, $characterMask);
default:
throw new Twig_Error_Runtime('Trimming side must be "left", "right" or "both".');
}
}
/**
* Escapes a string.
*
@@ -4,9 +4,21 @@
{{ " I like Twig. "|trim }}
{{ text|trim }}
{{ " foo/"|trim("/") }}
{{ " I like Twig. "|trim(side="left") }}
{{ " I like Twig. "|trim(side="right") }}
{{ " I like Twig. "|trim(null, "right") }}
{{ "/ foo/"|trim("/", "left") }}
{{ "/ foo/"|trim(character_mask="/", side="left") }}
{{ " do nothing. "|trim("", "right") }}
--DATA--
return array('text' => " If you have some <strong>HTML</strong> it will be escaped. ")
--EXPECT--
I like Twig.
If you have some &lt;strong&gt;HTML&lt;/strong&gt; it will be escaped.
foo
I like Twig.
I like Twig.
I like Twig.
foo/
foo/
do nothing.