Skip to content

Commit

Permalink
feat: port over Craft CMS Twig filter that adds support for using reg…
Browse files Browse the repository at this point in the history
…ex in the default Twig replace filter
  • Loading branch information
sghoweri committed Sep 3, 2019
1 parent 19e4c72 commit c11aa05
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 0 deletions.
1 change: 1 addition & 0 deletions packages/core-php/src/TwigExtensions/BoltCore.php
Expand Up @@ -105,6 +105,7 @@ public function getFunctions() {
public function getFilters() {
return [
Bolt\TwigFilters::json_decode(),
Bolt\TwigFilters::replaceFilter(),
];
}

Expand Down
24 changes: 24 additions & 0 deletions packages/core-php/src/TwigFilters.php
Expand Up @@ -6,6 +6,30 @@
use \Twig_SimpleFilter;

class TwigFilters {
// ported over from https://github.com/craftcms/cms/blob/develop/src/web/twig/Extension.php#L459
/**
* Replaces Twig's |replace filter, adding support for passing in separate
* search and replace arrays.
*
* @param mixed $str
* @param mixed $search
* @param mixed $replace
* @return mixed
*/
public static function replaceFilter() {
return new Twig_SimpleFilter('replace', function($str, $search, $replace = null) {
// Are they using the standard Twig syntax?
if (is_array($search) && $replace === null) {
return strtr($str, $search);
}
// Is this a regular expression?
if (preg_match('/^\/.+\/[a-zA-Z]*$/', $search)) {
return preg_replace($search, $replace, $str);
}
// Otherwise use str_replace
return str_replace($search, $replace, $str);
});
}

public static function markdown() {
return new Twig_SimpleFilter('markdown', function($string) {
Expand Down

0 comments on commit c11aa05

Please sign in to comment.