From 88bde29d85a66379b92bc78c60f3cee2c65536bd Mon Sep 17 00:00:00 2001 From: Chi Date: Sun, 10 Sep 2017 18:02:53 +0500 Subject: [PATCH] Issue #2906707 by hanoii: Improve preg_replace. --- src/TwigExtension.php | 7 ++++++- tests/src/Functional/TwigTweakTest.php | 6 +++++- tests/twig_tweak_test/templates/twig-tweak-test.html.twig | 3 ++- 3 files changed, 13 insertions(+), 3 deletions(-) diff --git a/src/TwigExtension.php b/src/TwigExtension.php index 9016ec4..676310f 100644 --- a/src/TwigExtension.php +++ b/src/TwigExtension.php @@ -384,7 +384,12 @@ class TwigExtension extends \Twig_Extension { * The new text if matches are found, otherwise unchanged text. */ public function pregReplaceFilter($text, $pattern, $replacement) { - return preg_replace("/$pattern/", $replacement, $text); + // BC layer. Before version 8.x-1.8 the pattern was without delimiters. + // @todo Remove this in Drupal 9. + if (strpos($pattern, '/') !== 0) { + return preg_replace("/$pattern/", $replacement, $text); + } + return preg_replace($pattern, $replacement, $text); } /** diff --git a/tests/src/Functional/TwigTweakTest.php b/tests/src/Functional/TwigTweakTest.php index 432a9d8..3108f5c 100644 --- a/tests/src/Functional/TwigTweakTest.php +++ b/tests/src/Functional/TwigTweakTest.php @@ -148,7 +148,11 @@ class TwigTweakTest extends BrowserTestBase { $this->assertByXpath($xpath); // Test preg replacement. - $xpath = '//div[@class = "tt-preg-replace" and text() = "foo-bar"]'; + $xpath = '//div[@class = "tt-preg-replace" and text() = "FOO-bar"]'; + $this->assertByXpath($xpath); + + // Test preg replacement (legacy). + $xpath = '//div[@class = "tt-preg-replace-legacy" and text() = "foo-bar"]'; $this->assertByXpath($xpath); // Test image style. diff --git a/tests/twig_tweak_test/templates/twig-tweak-test.html.twig b/tests/twig_tweak_test/templates/twig-tweak-test.html.twig index 59985e7..bf08269 100644 --- a/tests/twig_tweak_test/templates/twig-tweak-test.html.twig +++ b/tests/twig_tweak_test/templates/twig-tweak-test.html.twig @@ -36,7 +36,8 @@
{{ drupal_title() }}
{{ drupal_url('node/1', {absolute: true}) }}
{{ 'Site name: [site:name]' | token_replace }}
-
{{ 'foo' | preg_replace('(foo)', '$1-bar') }}
+
{{ 'FOO' | preg_replace('/(foo)/i', '$1-bar') }}
+
{{ 'foo' | preg_replace('(foo)', '$1-bar') }}
{{ 'public://images/ocean.jpg' | image_style('thumbnail') }}
{{ 'Привет!' | transliterate('ru') }}
{{ 'bold strong' | check_markup('twig_tweak_test') }}