Hot answers tagged

18

Twig has a replace filter for that. You can replace strings/vars with strings/vars: {% set string = "I love apples" %} {% set var = "like" %} {% set string = string|replace({'apples': 'kiwis', 'love': var}) %} {{ string }} {# Prints "I like kiwis" #} Your example: {% set rgb = "Red; Green; Blue" %} {% set rgb = rgb|replace({';': ','}) %} {{ rgb }} {# ...


7

Yes. {{ 'this is a string'|replace('/this is a (string)/', 'This is another $1') }} will output This is another string When you pass something that looks like a regex into the |replace filter, preg_replace() is called behind the scenes, so |replace can do anything preg_replace() can do.


7

I think you are getting the twig replace filter (which does not have the regex capability) instead of the Craft replace filter (which does). So this is a bug in Craft, in that their filter is masked by the twig one. You could use the trim filter to remove trailing /s: website|replace({'http://':''})|trim('/') Or you could use one of Victor's Twig PCRE ...


7

Use the raw filter on the replaced string (output), not block.body (input): {% set str = block.body %} {{ str | replace('<p>', '<p class="myClass" data-wow-duration="1s">') | raw }} Also, some friendly advice: I'd like to point out that rewriting HTML in this way is pretty risky. Shameless plug alert, but I wrote a plugin called Retcon HTML ...


5

Try using twig's raw filter. <h3>{{ jobs.jobStatement|replace({'%Job Title%': "<span class='highlight'>" ~ jobs.jobTitle ~ "</span>" })|raw }}</h3>


4

Currently it’s not possible to pass regex modifiers to the |replace filter. You’d have to just do this manually: {% set str = "foo \nbar " %} {% set trimmed = "" %} {% for line in str|split("\n") %} {% set trimmed = trimmed ~ (trimmed ? "\n") ~ line|replace('/\\s*$/', '') %} {% endfor %} UPDATE As of Craft 2.5, the |replace filter supports ...


4

Try doubling-up your backslashes: https://craftcms.com/docs/templating/filters#replace


3

It sounds like you'd be better off using Yii's Message Translations for this, if that's possible in your situation. They are what powers Craft's |t / |translate filter: {{ "String with {something} and {somethingElse}"|t('site', entry) }} With this, {something} and {somethingElse} would be replaced with the string values of entry.something and entry....


3

How about just using the replace filter? {% set text = "A small boat surrounds a large ​island​​" %} {% set linkedText = text|replace({'boat':'<a href="/whatever">boat</a>'}) %} {{ linkedText|raw }}<br><br> That works. In theory there should be a way to do it with parseRefs too, but my initial test isn't working yet: {% set ...


3

UPDATE: As of Craft v2.2, the replace filter now supports regex: The replace filter now supports regular expressions, by setting the first argument to a string that begins and ends with forward slashes, e.g. '/foo/'. So this should work by adding forward slashes. {% set bar = '/%20AND%20foo%3A%22(.+?)%22/' %} I think this is particular to Craft and not ...


3

Twig auto-escapes the \ character so by the time it makes it to the Craft replace filter PHP code, the regex string looks like /^d+.s/. By double escaping it, you're forcing the correct regex to make it through /^\d+\.\s/.


3

I'm just gonna post my comment as an answer, because I think it's the way to go. I'd use the kebab filter instead of url_encode, like this: {jobTitle|kebab}


2

Completely untested, but you should be able to do use something like the Craft-TwigPCRE plugin and some variation of this code: {% set text = "<p>Some text</p> tags as well as stuff like <strong>.|preg_replace('/\<p\>/', '') %} {% set text = text|preg_replace('/\<\/p\>/', '\\n') %} \n is the Line Feed control character for ...


2

Craft's replace filter only supports doing multiple strings replacements at once. If you want to do a regex replacement, it will have to be it's own separate call. In your case, you'd have to do something like this: {% set url = "http://www.google.com/"|replace('http://', '') %} {{ url|replace('/\\/$/', '') }}


2

You'd have to store the complete array into the variable {% set replaceHeadline = {'<h1>': '<p>', '</h1>': '</p>'} %} {{ entry.richText|replace(replaceHeadline)|raw }} But instead of storing that variable I'd probably just create a macro for that snippet. _includes/macros.html {% macro formatRichText(string) %} {{- string|...


2

I'd suggest a better approach as detailed here: https://experiencehq.net/blog/craft-with-markdown-and-matrix Once you go down the "structured content" route you'll never look back, I promise you :)


2

Well this feels like an awful kludge but at least I have it working with a finite number of image variables in the code below. There has to be a more elegant and flexible way to do this. And Natetronn, if your proposal does just that, perhaps you could help me see how. Otherwise, other cleverer folks, do let me know. {% for subsection in entry.subsections ...


2

This is partially side stepping your question but, it could be a solid option just the same: You might consider checking out Selvin's Doxter Markdown plugin. It has support for Entries, Assets, Users, Tags, Globals and Categories. This all via reference codes which can be copied and pasted into the Markdown as needed.


2

I have a Craft Helpers plugin on GitHub, which has a htmlEntityDecode Twig filter. {{ value|htmlEntityDecode}}


2

Doh! It was my ternary logic that was failing not the regex. I’m now doing this: {% set vidUrl = block.videoUrl %} {% if 'youtu' in vidUrl %} {# Check for an 'embed' URL which may need cleaning #} {% set vidId = 'embed' in vidUrl ? vidUrl|replace('/^http.*embed\\/([^\\?]+)(\\?.*)?$/', '$1') : null %} {# Check for a 'watch' URL which may need ...


2

In Twig, you never want to use delimiters inside other delimiters (e.g. {{ ... {{ ... }} }}). Here's how you would format it instead: <h3>{{ wordBoldTitle | replace('#', '<strong class="font-weight-extra-bold">' ~ entry.title ~ '</strong>') | raw }}</h3> What we're doing here is using Twig concatenation (via the ~ operator) to ...


1

Another way would be to create a Twig filter that does what is explained here replace only first appearance of string {{ str|replace_once() }}


1

I can't think of a way to do this with Twig's replace filter but it is possible to do it by splitting the text into an array and iterating over it like so: {% set content %} <p>Duis mollis, est non commodo luctus.</p> <p>Nulla vitae elit libero, a pharetra augue.</p> <p>Donec sed odio dui. Maecenas faucibus mollis ...


1

I would rather recommend to stick to semantic HTML and <ol> elements for your ordered lists. This not only makes showing the numbers easier, it really should be done out of accessibility reasons and it’s good practice in general. There are a couple of good solutions to modify the way numbers are displayed in ordered lists using CSS, if you are not ...


1

customAsciiCharMappings won't help you here. There is the "Find and Replace" tool available to admins (Settings->Tools) in the Control Panel, but its' a one-off thing and searches/replaces against all textual field types (Plain Text, Rich Text, etc. both inside and outside of Matrix fields). Honestly, probably just create a small Twig macro that wraps |...


1

As it happens, this solved my issue: {{ personfirstandlastname|replace({'\'':''}) }} EDIT To clarify, this isn't a valid Twig object: {'\'',''} ... while this is: {'\'':''}


1

A workaround in light of my comments on Brandon’s reply… If I ignore the attempt to act on child tags only, I can search for opening tags of all generated elements (regardless of whether they are nested) with… {% set elems = elems|replace('/(<[a-z][a-z0-9]*\\b[^>]*>)/', '$1>,') %} and then… {# Convert elems to an array #} {% set elems = ...


1

Backreferences within the regex are normally defined as \1, \2, etc. In the |replace filter you need to escape all backslashes, so it’ll be \\1, \\2, etc.


1

Assuming you only need this to work on the front end of your site (i.e., you don't actually need to see the links inside the Redactor field in the control panel), something like this might do the trick: {# Get the rich text content #} {% set text = entry.richTextField %} {# Get all entries that could possibly be linked #} {% set entries = craft.entries....


1

Just needed something similar today, and patched in a new replace filter to the RetconHTML plugin. The filter – called retconReplace – uses preg_replace and might be able to help you out: {{ string|retconReplace('/\s*$/m') }} You'll find the wiki on retconReplace here.


Only top voted, non community-wiki answers of a minimum length are eligible