Skip to content

Commit 1d29f45

Browse files
committed
feat: port over Craft CMS Twig filter that adds support for using regex in the default Twig replace filter
1 parent 2849ff4 commit 1d29f45

File tree

2 files changed

+25
-0
lines changed

2 files changed

+25
-0
lines changed

packages/core-php/src/TwigExtensions/BoltCore.php

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -105,6 +105,7 @@ public function getFunctions() {
105105
public function getFilters() {
106106
return [
107107
Bolt\TwigFilters::json_decode(),
108+
Bolt\TwigFilters::replaceFilter(),
108109
];
109110
}
110111

packages/core-php/src/TwigFilters.php

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,30 @@
66
use \Twig_SimpleFilter;
77

88
class TwigFilters {
9+
// ported over from https://github.com/craftcms/cms/blob/develop/src/web/twig/Extension.php#L459
10+
/**
11+
* Replaces Twig's |replace filter, adding support for passing in separate
12+
* search and replace arrays.
13+
*
14+
* @param mixed $str
15+
* @param mixed $search
16+
* @param mixed $replace
17+
* @return mixed
18+
*/
19+
public static function replaceFilter() {
20+
return new Twig_SimpleFilter('replace', function($str, $search, $replace = null) {
21+
// Are they using the standard Twig syntax?
22+
if (is_array($search) && $replace === null) {
23+
return strtr($str, $search);
24+
}
25+
// Is this a regular expression?
26+
if (preg_match('/^\/.+\/[a-zA-Z]*$/', $search)) {
27+
return preg_replace($search, $replace, $str);
28+
}
29+
// Otherwise use str_replace
30+
return str_replace($search, $replace, $str);
31+
});
32+
}
933

1034
public static function markdown() {
1135
return new Twig_SimpleFilter('markdown', function($string) {

0 commit comments

Comments
 (0)