diff --git a/system/src/Grav/Common/Twig/TwigExtension.php b/system/src/Grav/Common/Twig/TwigExtension.php index c1e7cefb3..a385bfe17 100644 --- a/system/src/Grav/Common/Twig/TwigExtension.php +++ b/system/src/Grav/Common/Twig/TwigExtension.php @@ -75,6 +75,7 @@ class TwigExtension extends \Twig_Extension new \Twig_SimpleFilter('modulus', [$this, 'modulusFilter']), new \Twig_SimpleFilter('rtrim', [$this, 'rtrimFilter']), new \Twig_SimpleFilter('pad', [$this, 'padFilter']), + new \Twig_SimpleFilter('regex_replace', [$this, 'regexReplace']), new \Twig_SimpleFilter('safe_email', [$this, 'safeEmailFilter']), new \Twig_SimpleFilter('safe_truncate', ['\Grav\Common\Utils', 'safeTruncate']), new \Twig_SimpleFilter('safe_truncate_html', ['\Grav\Common\Utils', 'safeTruncateHTML']), @@ -105,6 +106,7 @@ class TwigExtension extends \Twig_Extension new \Twig_SimpleFunction('nonce_field', [$this, 'nonceFieldFunc']), new \Twig_simpleFunction('random_string', [$this, 'randomStringFunc']), new \Twig_SimpleFunction('repeat', [$this, 'repeatFunc']), + new \Twig_SimpleFunction('regex_replace', [$this, 'regexReplace']), new \Twig_SimpleFunction('string', [$this, 'stringFunc']), new \Twig_simpleFunction('t', [$this, 'translate']), new \Twig_simpleFunction('ta', [$this, 'translateArray']), @@ -754,4 +756,19 @@ class TwigExtension extends \Twig_Extension return $string; } + + /** + * Twig wrapper for PHP's preg_replace method + * + * @param mixed $subject the content to perform the replacement on + * @param mixed $pattern the regex pattern to use for matches + * @param mixed $replace the replacement value either as a string or an array of replacements + * @param int $limit the maximum possible replacements for each pattern in each subject + + * @return mixed the resulting content + */ + public function regexReplace($subject, $pattern, $replace, $limit = -1) + { + return preg_replace($pattern, $replace, $subject, $limit); + } } diff --git a/tests/unit/Grav/Common/Twig/TwigExtensionTest.php b/tests/unit/Grav/Common/Twig/TwigExtensionTest.php index a0938838c..0600e4d94 100644 --- a/tests/unit/Grav/Common/Twig/TwigExtensionTest.php +++ b/tests/unit/Grav/Common/Twig/TwigExtensionTest.php @@ -137,6 +137,11 @@ class TwigExtensionTest extends \Codeception\TestCase\Test } + public function testRegexReplace() + { + + } + public function testUrlFunc() { @@ -169,7 +174,10 @@ class TwigExtensionTest extends \Codeception\TestCase\Test public function testArrayFunc() { - + $this->assertSame('this is my text', + $this->twig_ext->regexReplace('

this is my text

', '(<\/?p>)', '')); + $this->assertSame('this is my text', + $this->twig_ext->regexReplace('

this is my text

', ['(

)','(<\/p>)'], ['',''])); } public function testArrayKeyValue()