Custom Kirbytag at the end of a kirbytext & unnecessary markup

My content in the panel looks like this:

I use this kirbytext filter to detect custom kirbytags and include the corresponding snippets. This snippet close the open text-container of the kirbytext with (</p></div>), add the markup for the kirbytag and at the end it opens an new container (<div><p>) for the rest of the kirbytext. It works fine until you add a custom kirbytag at the end of the text. Then it open a new container and close this container directly. The markup is valid, but I would like to get rid of the unnecessary markup and empty containers.

So my question is: How can I detect if this custom kirbytag is the last content in the kirbytext. So I would not open a new container (<div><p).

You can specifically match the Kirbytag only if it is at the end with the RegEx !\(mytag:(.*?)\)$!is. By first replacing it without adding the tags and then replacing the other ones with the existing RegEx and with the tag addition, you can make sure that the last one does not get the tags.

Another solution: After you replaced everything, run preg_replace('!<div><p></p></div>$!', '', $text) to get rid of the tags at the end.

Great hint! Thanks @lukasbestle.

I try the way with preg_replace directly before returning the html inside the filter but it didn’t work. Is Kirby closing the open tags after running the post filters or is this wrong place for running the preg_replace? I would prefer this way over a custom regex for all kirbytags and the end.

Post filters are the last functions that modify the Kirbytext result. Are you sure that the tags are actually inserted on the server? Maybe your browser is putting them in dynamically. In that case, you need to modify my RegEx to be !<div><p>$!.

Thanks. I see the closing tags in the source-view. Did you mean this? My regex works if a copy the code from the source-view and test it separately.

What happens if you dump($text) the value inside your post filter?